Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format")  # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'
Answer from Martijn Pieters on Stack Overflow
Top answer
1 of 11
368

Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format")  # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'
2 of 11
152
>>> '{: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'      
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert an integer to binary with leading zeros in python
5 Best Ways to Convert an Integer to Binary with Leading Zeros in Python - Be on the Right Side of Change
February 18, 2024 - This code snippet creates a binary ... specified width. The zfill method in Python can be used to pad the binary string representation of an integer with zeros on the left, until it reaches a desired length....
Discussions

binary representation in Python and keeping leading zeros - Software Engineering Stack Exchange
Your decoder could use this information ... stored (with leading or trailing zeros, if you like). ... Both x and y hold integer values, you just choose to use 0b binary literals to define them. If you want to combine the two into z, you can easily do so using a shifting operation and binary bitwise operations: >>> x = 0b00010101010 >>> y = 0b1110000 >>> z = (x << 7) | y >>> bin(z) '0b101010101110000' Do note that python does not track ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
July 25, 2012
How to convert an integer to binary in Python and pad with leading zeros? - Ask a Question - TestMu AI (formerly LambdaTest) Community
I have used the following code to convert an integer to binary: >>> bin(6) '0b110' And when I want to remove the '0b' prefix, I use: >>> bin(6)[2:] '110' What can I do if I want to show the binary representation of 6 as 00000110 instead of just 110? How can I convert number to binary in Python and pad the result with leading zeros ... More on community.testmuai.com
🌐 community.testmuai.com
0
December 30, 2024
How to add zero’s to my binary number?
If you want to treat it as a number, you don't. The zeroes are basically already there, just not shown (much like how you wouldn't write 42 as 0042). If you want it as a string, or if you just want to print it out with leading zeroes, you can use string formatting for that. num = 0b1000000111100011111 print(f"{num:>024b}") More on reddit.com
🌐 r/learnpython
8
1
December 4, 2021
How would you add zeros to the beginning of an Integer, such that there are 4 total digits in the number?
zfill or format are not obscure at all. A python integer cannot have leading zeros. It's simply not possible. zfill and format work with strings. You can also use f-strings to add zeros to a string: data = 15 print(f"{data:0>4}") That said this sounds like an XY problem. We could help a lot more if you told us what problem you are trying to solve, not just how you are trying to solve it. What's the big picture here? http://xyproblem.info More on reddit.com
🌐 r/learnpython
4
2
February 16, 2022
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-140.php
Python: Convert an integer to binary keep leading zeros - w3resource
May 17, 2025 - # The 'format' function is used with the format specifier '08b' to format 'x' as an 8-character binary string. # It ensures that there are leading zeros to make it 8 characters long.
🌐
Codemia
codemia.io › home › knowledge hub › convert int to binary string in python
Convert int to binary string in Python | Codemia
January 9, 2025 - For a cleaner output without the 0b prefix, use format(n, 'b') or the equivalent f-string f'{n:b}'. For fixed-width binary with leading zeros, use a width specifier like f'{n:08b}'. This article covers all the built-in approaches, negative number handling, two's complement conversion, and manual ...
🌐
YouTube
youtube.com › vlogize
Converting Integer to Binary in Python with Leading Zeros - YouTube
Learn how to convert an integer to binary in Python while preserving leading zeros. Explore step-by-step instructions and examples for effective binary conve...
Published: March 2, 2024
Views: 32
Find elsewhere
Top answer
1 of 2
3

In Python, the 0b binary representation notation is just another way of writing integers. So there is no difference, for example, between 0b11 and 0b0011 - they both represent the integer 3.

Also, base64 encoding is designed for input data in 8-bit groups. The encoding is designed so that the decoder may determine exactly the number of bytes that were used in the original data. However, this granularity extends only to 8-bit groups and does not extend down to the actual bit level.

One approach might be to encode your data with the first byte representing the number of bits, and then the following bytes representing the actual bits themselves. Your decoder could use this information to extract the exact number of bits you originally stored (with leading or trailing zeros, if you like).

2 of 2
1

Both x and y hold integer values, you just choose to use 0b binary literals to define them.

If you want to combine the two into z, you can easily do so using a shifting operation and binary bitwise operations:

>>> x = 0b00010101010
>>> y = 0b1110000
>>> z = (x << 7) | y
>>> bin(z)
'0b101010101110000'

Do note that python does not track how many bits 'precision' you want to keep on such values; you defined y with 7 bits of information, so I had to shift x to the left 7 times to make room for y. You'd have to track this information yourself.

Your next problem is representing data as base64 as this format requires you to provide it with bytes only. That's chunks of 8 bits of binary data. This means you'll have to align your bits to the 8-bit boundaries and then turn these into bytes (e.g. strings). You won't be able to get around that, I'm afraid.

I'd use the struct module for that, it lets you pack integers and other data-types into bytes with ease:

>>> import struct
>>> struct.pack('>H', x)
'\x00\xaa'
>>> struct.pack('>H', x).encode('base64')
'AKo=\n'

In the above example I've packed the 11-bits x variable as an unsigned short (using the little-endian standard C format), resulting in 2 bytes of information, then encoded that to base64.

The reverse then requires decoding from base64, then an unpack operation:

>>> foo = struct.unpack('>H', 'AKo=\n'.decode('base64'))[0]
>>> bin(foo)
'0b10101010'

Again, Python doesn't track how many bits of information is important to you, you'll have to track that explicitly.

🌐
TestMu AI Community
community.testmuai.com › ask a question
How to convert an integer to binary in Python and pad with leading zeros? - Ask a Question - TestMu AI (formerly LambdaTest) Community
December 30, 2024 - I have used the following code to convert an integer to binary: >>> bin(6) '0b110' And when I want to remove the '0b' prefix, I use: >>> bin(6)[2:] '110' What can I do if I want to show the binary representation of 6…
🌐
YouTube
youtube.com › the python oracle
Convert to binary and keep leading zeros - YouTube
--------------------------------------------------Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn--------------------...
Published: May 20, 2024
Views: 7
🌐
Reintech
reintech.io › blog › python-bin-method-tutorial
Python: Working with the bin() Method - Reintech
March 24, 2023 - The bin() function works with any integer value, including positive numbers, negative numbers, and zero. Converting decimal integers to binary is straightforward with bin(). The function handles the conversion algorithm internally, representing numbers in base-2 format: decimal_value = 10 ...
🌐
Scaler
scaler.com › home › topics › python bin() function
Python bin() Function - Scaler Topics
January 2, 2024 - One important thing to remember is that bin() produces a string prefixed with 0b, indicating that the output is in binary format. This string can be altered further or utilized in various binary-related activities. Another essential feature is that bin() keeps leading zeros ...
🌐
w3resource
w3resource.com.cach3.com › python-exercises › python-basic-exercise-140.php.html
Python: Convert an integer to binary keep leading zeros - w3resource
May 28, 2022 - Converting an integer to an n-bit binary number results in its binary representation containing leading zeros up to length n. For example, to convert the integer 5 to a 6-bit binary results in 000101. format(num, name) function with name as "0nb" to ...
🌐
YouTube
youtube.com › how to fix your computer
PYTHON : Convert to binary and keep leading zeros - YouTube
PYTHON : Convert to binary and keep leading zeros [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : Convert to binary an
Published: December 5, 2021
Views: 45
🌐
Techie Delight
techiedelight.com › home › python › convert an integer to a binary string in python
Convert an integer to a binary string in Python | Techie Delight
July 7, 2026 - To convert the integer to its binary representation, you can use the string presentation type b. ... To get the binary string of specified length left-padded with all zeros, you can change the formatting specification to {0:08b}:
🌐
DNMTechs
dnmtechs.com › converting-to-binary-with-leading-zeros-in-python-3
Converting to Binary with Leading Zeros in Python 3 – DNMTechs – Sharing and Storing Technology Knowledge
In this example, we have an integer num with a value of 10. We use the format() function to convert it to a binary string with leading zeros. The '08b' format specifier tells Python to format the number as an 8-bit binary string with leading zeros.
🌐
Python Pool
pythonpool.com › home › tutorials › python int to binary: bin(), format(), and f-strings
Python int to Binary: bin(), format(), and f-strings
July 13, 2026 - Use bin for a prefixed representation, ... convert an integer to binary in Python, use bin(number) when you want the 0b prefix, or format(number, "b") when you want only the binary digits....
🌐
Finxter
blog.finxter.com › home › learn python blog › python bin() function
Python bin() Function – Be on the Right Side of Change
December 4, 2020 - Use the b format character to format the result as a binary. Python’s built-in bin(integer) function takes one integer argument and returns a binary string with prefix "0b".
🌐
Replit
replit.com › discover › how-to-convert-number-to-binary-in-python
How to convert a number to binary in Python
Browse coding tutorials, how-to guides, and product comparisons from Replit. Learn practical skills and choose the right tools to build faster.