Decimal to binary list conversion in Python

PythonServer Side ProgrammingProgramming

Python being a versatile language can handle many requirements that comes up during the data processing. When we need to convert a decimal number to a binary number we can use the following python programs.

Using format

We can Use the letter in the formatter to indicate which number base: decimal, hex, octal, or binary we want our number to be formatted. In the below example we take the formatter as 0:0b then supply the integer to the format function which needs to get converted to binary.

Example

Live Demo

Dnum = 11

print("Given decimal : " + str(Dnum))

# Decimal to binary number conversion
binnum = [int(i) for i in list('{0:0b}'.format(Dnum))]

# Printing result
print("Converted binary list is : ",binnum)

Output

Running the above code gives us the following result −

Given decimal : 11
Converted binary list is : [1, 0, 1, 1]

Using bin

The bin() is a in-built function which can also be used in a similar way as above. This function Python bin() function converts an integer number to a binary string prefixed with 0b. So we slice the first two characters.

Example

Live Demo

Dnum = 11

print("Given decimal : " + str(Dnum))

# Decimal to binary number conversion
binnum = [int(i) for i in bin(Dnum)[2:]]

# Printing result
print("Converted binary list is : ",binnum)



Output

Running the above code gives us the following result −

Given decimal : 11
Converted binary list is : [1, 0, 1, 1]
Published on 04-May-2020 13:00:41