Convert binary format string to int, in C

How do I convert a binary string like "010011101" to an int, and how do I convert an int, like 5, to a string "101" in C?


Solution 1:

The strtol function in the standard library takes a "base" parameter, which in this case would be 2.

int fromBinary(const char *s) {
  return (int) strtol(s, NULL, 2);
}

(first C code I've written in about 8 years :-)

Solution 2:

If it is a homework problem they probably want you to implement strtol, you would have a loop something like this:

char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
 total *= 2;
 if (*start++ == '1') total += 1;
}

If you wanted to get fancy you could use these in the loop:

   total <<= 1;
   if (*start++ == '1') total^=1;