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?
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 + ...
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) .
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With