How to Convert a Number from Binary to Decimal in Python
--
Would you like to learn how to convert a number from binary to decimal in Python? You are in the right place.
In Python, you represent binary numbers using 0b followed by the number. To convert a binary number to a decimal number Python provides the int() function. To convert the other way around, from decimal to binary, Python provides the bin() built-in function.
In this Python tutorial, we will cover a few examples to show you how to work with binary numbers in Python and how to convert numbers from the binary system to the decimal number system and vice-versa.
Let’s begin the conversion!
How to Convert Binary to Decimal Number in Python
As you know, the only two numbers you have in a binary number system are 0 and 1.
So, how can you convert a binary number into decimal using Python?
Let’s take, for example, the binary number 1010…
To specify a binary number in Python you have to use the prefix 0b. For example, you can write the binary number 1010 as 0b1010.
Let’s see what this looks like in the Python shell:
>>> number = 0b1010
And here is something interesting…
This is what you get back if you print this number.
>>> number
10
Even if we have specified a binary value, Python has stored this number as a decimal value.
Also…
To convert binary numbers to their decimal representation Python has a built-in function called int().
>>> int(0b1010)
10
How to Convert Decimal to Binary in Python
So, if you have a decimal number, how can you print it in using its binary format?
To print a number in binary format Python provides the built-in function bin().
Let’s use the bin() function to print the previous number in binary format:
>>> number = 10
>>> bin(number)
'0b1010'