[Python] Binary & Decimal Number Systems and how to convert between them
Photo by Mika Baumeister on Unsplash
Table of contents
Introduction
The binary and decimal number systems are important concepts in Mathematics, Computer Science and Digital electronics. And in almost all programming languages, we have some functions which help us convert numbers from one system to the other and vice versa. Python is no different. We have a few ways in which we can achieve this. Let us explore them.
Binary to decimal
We can use the int()
function with two arguments, first the string representation of the binary number and the second argument is the base, in this case 2.
Example:
n = '01100110'
print(f"The decimal representation of {n} is {int(n, 2)}")
will output
The decimal representation of 01100110 is 102
Decimal to binary
Python has the bin()
function which takes in a decimal integer and returns a string representation of its binary form
This string is preceded by '0b' which can be removed by the replace()
method
Example:
m = 18
print(f"{m} in binary is {bin(m).replace('0b', '')}")
this will print
18 in binary is 10010
We can also convert decimal to binary with the help of a format specifier, like
p = 4
print('{0:b}'.format(p))
will print 100
That is it for this article. Hope you found this helpful. Please share your thoughts in the comments below.