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
367

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'      
🌐
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 '010b' to format 'x' as a 10-character binary string. # It ensures that there are leading zeros to make it 10 characters long. print(format(x, '010b')) ... Write a Python function to ...
Discussions

Convert decimal to binary in python - Stack Overflow
Is there any module or function in python I can use to convert a decimal number to its binary equivalent? I am able to convert binary to decimal using int('[binary_value]',2), so any way to do the More on stackoverflow.com
🌐 stackoverflow.com
Converting from decimal to binary in Python
So this is a pretty complicated topic for a beginner called recursion. I'll try my best to explain what's going on. The last line print(n % 2, end="") simply prints the remainder after n is divided by 2. This will be either 1 or 0 since 2 goes into all larger numbers atleast once. By default python puts a new line character after every print and the 'end=""' simply says 'print nothing at the end' instead of the normal 'print \n at the end' (\n indicates a newline) Now for the fun part. Let's step through what happens with n=10. In binary we know this is represented by '1010'. When n is 10 we see it is greater than 1, so we execute line 3 (dec2bin(n//2)). This basically pauses what we're currently doing for now and starts over with a different value. You can think of this like a stack of boxes. Originally we just have our one box, when we call dec2bin again we put another box on top. We can't keep working on the bottom box anymore because it's covered. We need to finish the top box so we can remove it and get to the bottom box again. I should mention that // means integer division. 3//2 is 1 because 2 goes into 3 one whole time. So in our stack of boxes (aka our call stack) we will have: dec2bin(5) dec2bin(10) So let's work through what happens when we call dec2bin(5). It's important to note that 5 is '101' in binary which is the same as 10 ('1010') except the last 0 disappears because of the division. 5 is greater than 1 so we execute line 3 and call dec2bin again! Gotta put another box on top of our call stack: dec2bin(2) dec2bin(5) dec2bin(10) Note that 2 in binary is '10', which is the same as ten in binary except drop the last two digits because we did division twice. Working through dec2bin(2) we get another call to dec2bin: dec2bin(1) dec2bin(2) dec2bin(5) dec2bin(10) Printed: nothing Now this is where it gets interesting. Working through dec2bin(1) we have n=1. In this case n is NOT greater than 1 (line 2). So we continue on and print 1%2 which is 1. Now the function finishes and we're done with this call of dec2bin(1) so we can remove it from the call stack: dec2bin(2) dec2bin(5) dec2bin(10) Printed: '1' Now dec2bin(2) we paused on line 3, but line 3 just finished up so we can continue onto line 4 and print 2%2 which is 0. We've printed '10' so far. Again the function finishes up and we remove it from the call stack. dec2bin(5) dec2bin(10) Printed: '10' dec2bin(5) was paused on line 3, it continues now. We print 5%2 which is 1. The function finishes. It gets removed from the call stack. dec2bin(10) Printed: '101' We've finished up most of the pile back down to our original call. It (finally) runs its line 4 and prints 10%2, which is 0. We've printed '1010'. The function finishes up and we're all done. Printed: '1010' I hope that I haven't just confused you further, recursion is a tough topic to understand especially if not explained in a way that makes sense to you. More on reddit.com
🌐 r/learnpython
9
15
July 24, 2019
How to convert an integer to binary in Python and pad with leading zeros? - Ask a Question - TestMu AI 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 ... More on community.testmuai.com
🌐 community.testmuai.com
0
December 30, 2024
Convert decimal input to 8 bit binary
https://letmegooglethat.com/?q=python+dec+to+bin More on reddit.com
🌐 r/pythontips
7
1
October 29, 2023
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.

🌐
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 - The rjust method can be employed to right-justify the binary string, padding it with zeros on the left side to achieve a given width. This is done after converting the integer to a binary string, excluding the “0b” prefix. ... In this snippet, the bin() function converts the integer to binary, the slicing operation removes the “0b” prefix, and rjust() adds leading zeros to reach the specified width...
🌐
Reddit
reddit.com › r/learnpython › converting from decimal to binary in python
r/learnpython on Reddit: Converting from decimal to binary in Python
July 24, 2019 -

Would someone be willing to help me (total beginner) understand how this converts decimal values to binary? Maybe just by explaining what happens line by line?

def dec2bin(n):
    if n > 1:
        dec2bin(n//2)
    print(n % 2, end="")

It's just not intuitive at all for me :/

Any help would be greatly appreciated!

Top answer
1 of 4
19
So this is a pretty complicated topic for a beginner called recursion. I'll try my best to explain what's going on. The last line print(n % 2, end="") simply prints the remainder after n is divided by 2. This will be either 1 or 0 since 2 goes into all larger numbers atleast once. By default python puts a new line character after every print and the 'end=""' simply says 'print nothing at the end' instead of the normal 'print \n at the end' (\n indicates a newline) Now for the fun part. Let's step through what happens with n=10. In binary we know this is represented by '1010'. When n is 10 we see it is greater than 1, so we execute line 3 (dec2bin(n//2)). This basically pauses what we're currently doing for now and starts over with a different value. You can think of this like a stack of boxes. Originally we just have our one box, when we call dec2bin again we put another box on top. We can't keep working on the bottom box anymore because it's covered. We need to finish the top box so we can remove it and get to the bottom box again. I should mention that // means integer division. 3//2 is 1 because 2 goes into 3 one whole time. So in our stack of boxes (aka our call stack) we will have: dec2bin(5) dec2bin(10) So let's work through what happens when we call dec2bin(5). It's important to note that 5 is '101' in binary which is the same as 10 ('1010') except the last 0 disappears because of the division. 5 is greater than 1 so we execute line 3 and call dec2bin again! Gotta put another box on top of our call stack: dec2bin(2) dec2bin(5) dec2bin(10) Note that 2 in binary is '10', which is the same as ten in binary except drop the last two digits because we did division twice. Working through dec2bin(2) we get another call to dec2bin: dec2bin(1) dec2bin(2) dec2bin(5) dec2bin(10) Printed: nothing Now this is where it gets interesting. Working through dec2bin(1) we have n=1. In this case n is NOT greater than 1 (line 2). So we continue on and print 1%2 which is 1. Now the function finishes and we're done with this call of dec2bin(1) so we can remove it from the call stack: dec2bin(2) dec2bin(5) dec2bin(10) Printed: '1' Now dec2bin(2) we paused on line 3, but line 3 just finished up so we can continue onto line 4 and print 2%2 which is 0. We've printed '10' so far. Again the function finishes up and we remove it from the call stack. dec2bin(5) dec2bin(10) Printed: '10' dec2bin(5) was paused on line 3, it continues now. We print 5%2 which is 1. The function finishes. It gets removed from the call stack. dec2bin(10) Printed: '101' We've finished up most of the pile back down to our original call. It (finally) runs its line 4 and prints 10%2, which is 0. We've printed '1010'. The function finishes up and we're all done. Printed: '1010' I hope that I haven't just confused you further, recursion is a tough topic to understand especially if not explained in a way that makes sense to you.
2 of 4
1
by the case you just didn´t figure it out with the answers already posted. Try using Python Tutor http://pythontutor.com/visualize.html#mode=edit paste the code there and visualize what happens
🌐
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 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 as 00000110 instead of just 110? How can I convert number to binary in Python ...
🌐
YouTube
youtube.com › watch
How to Convert a Decimal Number to a Binary Format with Leading Zeros in Python - YouTube
Learn how to easily convert decimal numbers to binary format in Python, ensuring that you include leading zeros for better readability.---This video is based...
Published   May 26, 2025
Views   0
Find elsewhere
🌐
Python Guides
pythonguides.com › convert-decimal-numbers-to-binary-in-python
Convert Decimal Numbers to Binary in Python
February 15, 2025 - In this method, we use the bitwise AND operator (&) to extract the least significant bit of the decimal number in each iteration. We then right-shift the decimal number by 1 using the >>= operator to move to the next bit.
🌐
Reddit
reddit.com › r/pythontips › convert decimal input to 8 bit binary
r/pythontips on Reddit: Convert decimal input to 8 bit binary
October 29, 2023 -

Hi all i'm very new to coding (a few weeks) and Python and was wondering if there is a way to get an input of a decimal number and convert it to 8 bit binary. Currently using the Thonny IDE

🌐
Quora
quora.com › How-do-I-create-a-program-that-converts-decimal-to-binary-in-Python
How to create a program that converts decimal to binary in Python - Quora
Convert a number from decimal (with no more than seven digits after decimal point) to binary, octal, hexadecimal, or base N ... Move remainder to left end of Binary number representation. Move quotient to beginning of next line. Keep repeating until you get to zero.
🌐
Quora
quora.com › Is-there-any-way-to-remove-0-from-binary-and-then-regain-add-the-same-amount-0-in-binary-in-Python
Is there any way to remove 0 from binary and then regain add the same amount 0 in binary in Python? - Quora
0010 (a value of 2). If it is shifted to the right, you would want a zero fill to provide 0001 (half of 2). If shifting to the left, you want the 0010 to be 0100 (value 4), If you filled with 1 on the left, the value would be 5. Depending upon the computer hardware design, the negative number may be the 2’s complement of the positive number or ... For more detailed information, search the internet for two’s complement and signed numbers. ... When a decimal number is converted into binary in Python, making it a string (eg.
🌐
Python
bugs.python.org › issue14694
Issue 14694: Option to show leading zeros for bin/hex/oct - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/58899
🌐
Reintech
reintech.io › blog › python-bin-method-tutorial
Python: Working with the bin() Method | Reintech media
January 20, 2026 - 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 ...
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-185.php
Python: Convert a given decimal number to binary list - w3resource
June 28, 2025 - Write a Python program to convert a decimal number to a binary list and pad it to a specified length with leading zeros.
🌐
Scaler
scaler.com › home › topics › python bin() function
Python bin() Function - Scaler Topics
January 2, 2024 - It divides the input number by two indefinitely, capturing the remainder until the quotient equals zero. To create the binary representation, the remainders are inverted. In this section, we're going to look at the function bin in Python and show how to use it using a series of code samples. ... bin(10) converts the decimal number 10 to its binary representation, resulting in the string '0b1010'.
🌐
PYnative
pynative.com › home › python › programs and examples › python convert decimal number to binary and vice versa
Python Convert Decimal Number to Binary and Vice Versa – PYnative
April 22, 2025 - The bin() function in Python converts an integer number into its binary string representation. ... Returns a string that starts with '0b', followed by the binary representation of the integer. ... Note: [2:] slices a string from index 2 to the end, skipping the first two characters. decimal ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-covert-decimal-to-binary-number
Convert Decimal to Binary Number - Python
n = 7 # decimal number res = '' # binary result while n > 0: res = str(n & 1) + res n >>= 1 print(res) ... Explanation: while loop extracts the least significant bit of n using n & 1, prepends it to res and right-shifts n (n >>= 1) to process ...
Published   July 11, 2025
🌐
Solved
code.i-harness.com › en › q › 10245b2
zeros - python program to convert integer to binary - Solved
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: