Convert unsinged integer to binary string



Convert binary string to unsigned integer



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


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,



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)


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,