Link to home
Start Free TrialLog in
Avatar of DPhoenix121
DPhoenix121

asked on

Convert binary string to decimal, strtol()

I have a program that receives a string in binary format.  The string is a signed binary number between -511 and 512.  I need to convert the string into an int to perform some mathmatical operations on it.  I used the strtol function to convert the string, but it always treats the 10 binary digits as unsigned.  How do I convert the binary string so that it is signed?

All strings are 10 characters long, consisting of only a 1 or a 0. ie. "1111111111" should be converted to -1, not 1023.

I have
int conv (string bnum) {
     int dnum = strtol(bnum.c_str(),&pEnd,2);
     return dnum;
}

But it's not working, HELP!!!
ASKER CERTIFIED SOLUTION
Avatar of chip3d
chip3d
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
strtol will convert your string to a 32 bit value:
"1111111111" -> 00000000000000000000001111111111 -> 1023

you need:
11111111111111111111111111111111 -> -1

bit 10 of your string indicates whether you have a signed or unsigned value:
with the mask 0x200 you can check if this bit is set or not
if (dnum & 0x200)

if so, you have to overwrite all the zeros with ones
dnum |= 0xfffffc00
Avatar of zulti
zulti

if (dnum >= 512)
   dnum -= 1024 ;
Avatar of DPhoenix121

ASKER

Excellent, worked like a charm.  Thanks chip3d