Convert Int to Binary in Python
Last modified: 2023-08-29
Using the format method in Python, we can convert int to binary.
Conversion
Int -> N-bit
Specify 'b' in the format
method in Python.
format(123, 'b')
# 1111011
Int -> 8-bit
We can specify 8-bit
by prepending {0:08b}
before the format
method.
Alternatively, zfill
method can be used for this purpose.
'{0:08b}'.format(123, 'b')
format(123, 'b').zfill(8)
# 01111011
Int -> 16-bit
This is also the same as above, we can specify 16-bit
by prepending {0:016b}
, or zfill
method can be used.
'{0:016b}'.format(123, 'b')
format(123, 'b').zfill(16)
# 0000000001111011