user1777711
user1777711

Reputation: 1744

C++ converting binary(64 bits) to decimal

I using string to contain my 64 bits binary.

string aBinary;
aBinary = "100011111011101100000101101110000100111000011100100100110101100";

Initially i tried this..

stringstream ss;
ss << bitset<64>(aBinary).to_ulong();
buffer = ss.str();

cout << buffer << endl;

Its work for some binary, but this one it doesn't work. How can i convert the above 64 bits binary that is contain in a string container into a decimal which is of a string container too.

Upvotes: 0

Views: 1342

Answers (2)

Rick
Rick

Reputation: 11

maybe you can done it with C:

char *Str = "0100011111011101100000101101110000100111000011100100100110101100";
char *ptr = NULL;
unsigned long long toValue;

toValue = 0;

ptr = Str + strlen(Str) - 1;
for(int i = 0 ; i < strlen(Str) , ptr != Str ; i++,ptr--)
{
    if(*ptr != '0')
        toValue += ((unsigned long long)1 << i);
}

printf("%d\n",toValue);

Upvotes: 0

paddy
paddy

Reputation: 63461

It's overflowing, because to_ulong() is 32-bits.

C++-11 introduces the function to_ullong(), which is what you want. If you don't have that, you can try splitting your string into two, get two 32-bit numbers, convert to 64-bit, do a shift and an add.

Upvotes: 1

Related Questions