[python] Converting integer to binary in python

In order to convert an integer to a binary, I have used this code :

>>> bin(6)  
'0b110'

and when to erase the '0b', I use this :

>>> bin(6)[2:]  
'110'

What can I do if I want to show 6 as 00000110 instead of 110?

This question is related to python binary integer

The answer is


You can use just:

"{0:b}".format(n)

In my opinion this is the easiest way!


('0' * 7 + bin(6)[2:])[-8:]

or

right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side

Going Old School always works

def intoBinary(number):
binarynumber=""
if (number!=0):
    while (number>=1):
        if (number %2==0):
            binarynumber=binarynumber+"0"
            number=number/2
        else:
            binarynumber=binarynumber+"1"
            number=(number-1)/2

else:
    binarynumber="0"

return "".join(reversed(binarynumber))

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")

.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'

Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.

could be useful when you apply binary to power sets

import numpy as np
np.binary_repr(6, width=8)

The best way is to specify the format.

format(a, 'b')

returns the binary value of a in string format.

To convert a binary string back to integer, use int() function.

int('110', 2)

returns integer value of binary string.


def int_to_bin(num, fill):
    bin_result = ''

    def int_to_binary(number):
        nonlocal bin_result
        if number > 1:
            int_to_binary(number // 2)
        bin_result = bin_result + str(number % 2)

    int_to_binary(num)
    return bin_result.zfill(fill)

A bit twiddling method...

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'

numpy.binary_repr(num, width=None) has a magic width argument

Relevant examples from the documentation linked above:

>>> np.binary_repr(3, width=4)
'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=5)
'11101'

eumiro's answer is better, however I'm just posting this for variety:

>>> "%08d" % int(bin(6)[2:])
00000110

even an easier way

my_num = 6
print(f'{my_num:b}')

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'

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 integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?