Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary format string to int, in C

Tags:

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?

like image 251
Yongwei Xing Avatar asked Feb 26 '10 16:02

Yongwei Xing


People also ask

How do you convert binary to integer?

The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n): decimal = d0×20 + d1×21 + d2×22 + ...

How do you convert a string to a binary number?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .


1 Answers

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 :-)

like image 123
Pointy Avatar answered Sep 24 '22 01:09

Pointy