Converting the string to int
is easy: start with a zero int
, then go through the characters of the binary representation, and check if it is zero or one. First, shift the partial result to the left. Then, if the digit is one, OR the result with 1
. Continue to the next character. When you see null terminator '\0'
, stop.
Here is some pseudocode:
res = 0
ptr = "00000000011101"
while ptr is not pointing to '\0'
res <<= 1;
if ptr points to '1'
res |= 1;
Once you have your int
, getting the last three bits is equivalent to AND-ing &
the result with seven (its binary representation is 0000111
). Getting the rest of the bits is equivalent to shifting >>
the number right by three.
Here is some pseudocode:
lastThree = res & 7
topBits = res >> 3