Today I learned how to convert an integer to binary string format in python using standard functions available.

binary_string = format(n, ‘0Nb’)

where N is the number of digits we need

>>> format(10)
'10'
>>> format(10, 'b')
'1010'
>>> format(10, '9b')
'     1010'
>>> format(10, '09b')
'000001010'

I also found another way to convert binary string back to integer.

integer = int(binary_string, 2)

Now, this means the following python statement will always be true for any integer (I guess there are no edge cases here but maybe I’m wrong):

assert integer == int(format(integer, ‘b’), 2)

~ updated at: 2026-03-08T12:08:11.952Z