c++stringbinarytwos-complement

How do I convert a string of binary numbers to their signed decimal representation using C++?


I have a string:

1010

The unsigned representation of the string comes out be 10 after doing:

string immediateValue = "1010";
char immediateChars[5];
strcpy(immediateChars, immediateValue.c_str());

char * ptr;
long parsedInteger = strtol(immediateChars, &ptr, 2);

As I understand strtol can be used to only get unsigned representation. Is there a way to get the 2's complement value which would be -6?


Solution

  • Check your first character, if it is 0 then use n = strtol normally, if it is 1 then flip the bits, e.g. "1010" to "0101", then take strtol of the flipped string, the negative of that value minus one is your answer.