[python] Convert to binary and keep leading zeros in Python

I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:

Example:

bin(1) -> 0b1

# What I would like:
bin(1) -> 0b00000001

Is there a way of doing this?

This question is related to python binary formatting bitwise-operators

The answer is


You can use something like this

("{:0%db}"%length).format(num)

you can use rjust string method of python syntax: string.rjust(length, fillchar) fillchar is optional

and for your Question you acn write like this

'0b'+ '1'.rjust(8,'0)

so it wil be '0b00000001'


>>> '{:08b}'.format(1)
'00000001'

See: Format Specification Mini-Language


Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use

>>> '{0:08b}'.format(1)
'00000001'      

You can use zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

prints:

01
10
100

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. - x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.


When using Python >= 3.6, the cleanest way is to use f-strings with string formatting:

>>> var = 23
>>> f"{var:#010b}"
'0b00010111'

Explanation:

  • var the variable to format
  • : everything after this is the format specifier
  • # use the alternative form (adds the 0b prefix)
  • 0 pad with zeros
  • 10 pad to a total length off 10 (this includes the 2 chars for 0b)
  • b use binary representation for the number

Sometimes you just want a simple one liner:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3


You can use the string formatting mini language:

def binary(num, pre='0b', length=8, spacer=0):
    return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])

Demo:

print binary(1)

Output:

'0b00000001'

EDIT: based on @Martijn Pieters idea

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

I am using

bin(1)[2:].zfill(8)

will print

'00000001'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to binary

Difference between opening a file in binary vs text Remove 'b' character do in front of a string literal in Python 3 Save and retrieve image (binary) from SQL Server using Entity Framework 6 bad operand types for binary operator "&" java C++ - Decimal to binary converting Converting binary to decimal integer output How to convert string to binary? How to convert 'binary string' to normal string in Python3? Read and write to binary files in C? Convert to binary and keep leading zeros in Python

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to bitwise-operators

What is (x & 1) and (x >>= 1)? Convert to binary and keep leading zeros in Python What does AND 0xFF do? What is Bit Masking? Why do we usually use || over |? What is the difference? What does a bitwise shift (left or right) do and what is it used for? What is the difference between & and && in Java? Differences in boolean operators: & vs && and | vs || How does bitshifting work in Java? Getting each individual digit from a whole integer