Converting integer to binary in python
>>> '{0:08b}'.format(6)
'00000110'
Just to explain the parts of the formatting string:
-
{}
places a variable into a string -
0
takes the variable at argument position 0 -
:
adds formatting options for this variable (otherwise it would represent decimal6
) -
08
formats the number to eight digits zero-padded on the left -
b
converts the number to its binary representation
If you're using a version of Python 3.6 or above, you can also use f-strings:
>>> f'{6:08b}'
'00000110'
Just another idea:
>>> bin(6)[2:].zfill(8)
'00000110'
Shorter way via string interpolation (Python 3.6+):
>>> f'{6:08b}'
'00000110'