// bintodec.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
 
using namespace std;
 
int main(){
        string inp;
        int dec = 0;
        char base;
        cout << "Input a number: ";
        cin >> inp;
        cout << "Input the base your number is in: ";
        cin >> base;
        for(int i = inp.length()-1, j = 0; i >= 0; i--, ++j) dec += (inp[i]-48) * pow((float)base-48, j);
        cout << "Your number in base 10 is: " << dec <<endl;
        system("pause");
return 0;
}

hey all can some1 tell me the logic in this code??

like an example of what happens if input a NUMBER and BASE

TY!!

Recommended Answers

All 3 Replies

What happens when you compile it and run it?

it works perfectly..I just want to understand the logic of how its doing it, specifically:

for(int i = inp.length()-1, j = 0; i >= 0; i--, ++j) dec += (inp[i]-48) * pow((float)base-48, j);

it works perfectly..I just want to understand the logic of how its doing it, specifically:

for(int i = inp.length()-1, j = 0; i >= 0; i--, ++j) dec += (inp[i]-48) * pow((float)base-48, j);

Here,
i= the digit from lower place value to higher place value(initially i=digit in ones' place)
j= the power to which the base is raised to(starts from zero)
And the same old formula of converting a number (in any base ) to the decimal format.
for e.g. in a number with four digits,i starts at 3 and j starts at 0.

...+inp[i-3]*base^(j+3)+inp[i-2]*base^(j+2)+inp[i-1]*base^(j+1)+inp[i]*base^j

Suppose the number is 3751 in base 8,then

3*8^3 + 7*8^2 + 5*8^1 + 1*8^0 = 2025 in base 10

Note: inp-48 converts each char(which is in ascii) to decimal.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.