answersLogoWhite

0


Best Answer

The following code will convert any number in any base to any other base, from binary to hexadecimal, and everything inbetween.

#include<iostream>

#include<string>

#include<sstream>

typedef unsigned long long ull;

typedef unsigned long ul;

const std::string symbols="0123456789abcdef";

std::string inputvalue(ul base)

{

using namespace std;

string value;

while(1)

{

cout<<"Enter a positive value : ";

string s;

getline(cin,s);

if(s.size())

{

for(string::iterator i=s.begin();i!=s.end();++i)

if(*i>='A' && *i<='Z')

*i+=32;

string actual = symbols.substr(0,base);

if(s.find_first_not_of(actual)!=string::npos)

{

cout<<"The value you entered is invalid for the base.\n"

<<"Please enter another value.\n"<<endl;

continue;

}

value=s;

break;

}

}

return(value);

}

ul inputbase(std::string prompt)

{

using namespace std;

ul result=0, min=2, max=16;

while(1)

{

cout<<prompt.c_str()<<" ["<<min<<".."<<max<<"] : ";

string s;

getline(cin,s);

if(s.size())

result=stoul(s,0,10);

if(result<min result>max)

cout<<"The base must be in the range "

<<min<<".."<<max<<"\n"

<<"Please enter another base.\n"<<endl;

else

break;

}

return(result);

}

ull base2dec(std::string value,ul base)

{

ull col=1, num=0;

for(std::string::reverse_iterator i=value.rbegin(); i!=value.rend(); ++i)

{

num+=symbols.find(*i,0)*col;

col*=base;

}

return(num);

}

std::string dec2base(ull dec,ul base)

{

using namespace std;

int len=1;

ull tmp=dec;

while(tmp/=base)

++len;

string value("0",len);

while(dec)

{

value[--len]=symbols[dec%base];

dec/=base;

}

return(value);

}

int main()

{

using namespace std;

ul base=inputbase("Enter the base of the value");

string value=inputvalue(base);

ul newbase=inputbase("Enter the base to convert to");

value=dec2base(base2dec(value,base),newbase);

cout<<"New value:\t"<<value.c_str()<<endl;

return(0);

}

User Avatar

Wiki User

10y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How can you convert binary number into decimal number using g plus plus compiler?
Write your answer...
Submit
Still have questions?
magnify glass
imp