Link Search Menu Expand Document

Convert binary to decimal

Let us explore how to convert a number from binary to decimal representation. Here is an example of such a conversion:

  • πŸ€– The binary number 11011.
  • πŸ’― The decimal number 27.

This conversion is performed by summing powers of two. In this case, it is 2^4 + 2^3 + 2^1 + 2^0. The power 2^2 is skipped because there is a 0 in that position.

This process is similar to decimal representation, except the base is 2 instead of 10. For instance, the number 27 is actually 2*10^1 + 7*10^0, or simply 27.

We can create our function as follows. We add 2 raised to the appropriate power, using the digit, which is either 0 or 1.

def binary_to_decimal(binary):
    decimal = 0
    power = 0
    for digit in reversed(binary):
        if digit not in {'0', '1'}:
            raise ValueError("Invalid binary number.")
        decimal += int(digit) * (2 ** power)
        power += 1

    return decimal

We can use the function as follows:

binary = "11011"
decimal = binary_to_decimal(binary)
print(f"{binary} -> {decimal}")
# 11011 -> 27

✏️ Exercises:

  • Write a decimal_to_binary function that performs the reverse conversion, from decimal to binary.