Traditional method to Convert Python int to Binary (without any function): Firstly, divide the number by 2 and add the remainder to a list. Then continue step 1 till the number is greater than 0. After this, reverse the list.
Python bin() Without '0b' Prefix To skip the prefix, use slicing and start with index 2 on the binary string. For example, to skip the prefix '0b' on the result of x=bin(2)='0b10' , use the slicing operation x[2:] that results in just the binary number '10' without the prefix '0b' .
>>> '{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'
A bit twiddling method...
>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'
Just use the format function
format(6, "08b")
The general form is
format(<the_integer>, "<0><width_of_string><format_specifier>")
eumiro's answer is better, however I'm just posting this for variety:
>>> "%08d" % int(bin(6)[2:])
00000110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With