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!!!
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,
return dnum;
}
But it's not working, HELP!!!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
if (dnum >= 512)
dnum -= 1024 ;
dnum -= 1024 ;
ASKER
Excellent, worked like a charm. Thanks chip3d
"1111111111" -> 00000000000000000000001111
you need:
11111111111111111111111111
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