Convert unsinged integer to binary string

bin(10)

‘0b1010’

Convert binary string to unsigned integer

int('1010',2)

10

It also works if you try the binary string with the prefix ‘0b’. For example,

int('0b1010',2)

Convert signed integer to binary string

It is a little bit difficult to deal with negative numbers. Trying to convert it the same way we did with unsigned numbers doesn’t work as expected,

bin(-10)

’-0b1010’

You would have expected a Two’s complement number as the output but it just prints the binary string of positive number with a ‘-’ prefix. This problem can be fixed by specifying the length of the bits you want as output.

bin(-10 & 0xff)

‘0b11110110’

If you want the length to be dynamic,

int("1" * 8, 2)

Convert singed binary string to signed integer

I am not sure if there is a direct way to do this in python. If you find any please let me know! I have written a small function to do it,