How to convert binary to decimal in Python
Published on Aug. 22, 2023, 12:16 p.m.
To convert a binary number to a decimal integer in Python, you can use the int()
function with a base parameter of 2. The int()
function takes a string or a number as input and converts it to an integer. When given a string, the base parameter specifies the base of the number system to be used (in this case, base 2 for binary). Here’s an example:
my_binary = "101101"
my_decimal = int(my_binary, 2)
print(my_decimal) # Output: 45
In this example, we define a binary string my_binary
containing the value 101101
. We use the int()
function to convert the binary string into a decimal integer called my_decimal
. The resulting value in my_decimal
is equivalent to the original value in my_binary
, but converted to decimal format.
If the binary string includes non-binary characters (i.e., characters that are not ‘0’ or ‘1’), the int()
function will raise a ValueError. You can catch this exception using a try-except block to handle the error gracefully.
In general, converting a binary number to a decimal integer can be useful when you need to perform arithmetic operations involving binary numbers or when passing binary values as arguments to functions that expect decimal integers.