In order to convert an integer to a binary, I have used this code :
>>> bin(6)
'0b110'
and when to erase the '0b', I use this :
>>> bin(6)[2:]
'110'
What can I do if I want to show 6 as 00000110 instead of 110?
>>> '{0:08b}'.format(6)
'00000110'
Just to explain the parts of the formatting string:
{} places a variable into a string0 takes the variable at argument position 0: adds formatting options for this variable (otherwise it would represent decimal 6)08 formats the number to eight digits zero-padded on the leftb converts the number to its binary representationIf 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'
numpy.binary_repr(num, width=None) has a magic width argumentRelevant examples from the documentation linked above:
>>> np.binary_repr(3, width=4) '0011'The two’s complement is returned when the input number is negative and width is specified:
>>> np.binary_repr(-3, width=5) '11101'