Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1672
  • Last Modified:

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!!!
0
DPhoenix121
Asked:
DPhoenix121
  • 2
1 Solution
 
chip3dCommented:
this will do the work:

int conv (const char *str)
{
     char *end = 0;
     short dnum = strtol(str,&end,2);
     if (dnum & 0x200) dnum |= 0xfc00;
     return dnum;
}

0
 
chip3dCommented:
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
0
 
zultiCommented:
if (dnum >= 512)
   dnum -= 1024 ;
0
 
DPhoenix121Author Commented:
Excellent, worked like a charm.  Thanks chip3d
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now