How to Convert Integer to Binary in Python
In this article, we will see how to convert integer to binary in Python.
Suppose we have an integer of value 12 with us, and we need to find the binary equivalent of this integer.
One way is to use bin()
function.
# simply using bin(). This will produce '0b' in the left end >>> bin(12) '0b1100' # to avoid '0b', you can use index slicing >>> bin(12)[2:] '1100' # zfill(8) will put 8 zeros on the left >>> bin(12)[2:].zfill(8) '00001100' >>> bin(12)[2:].zfill(10) '0000001100'
Or you can use format()
>>> '{0:08b}'.format(12) '00001100' >>> '{0:b}'.format(12) '1100'
{}
places a variable into a string0
takes the variable at argument position 0:
adds formatting options for this variable (otherwise it would represent decimal 12)08
formats the number to eight digits zero-padded on the leftb
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'{12:08b}' '00001100'
Subscribe
Login
Please login to comment
0 Discussion