Convert a binary number to decimal number

Binary and decimal are two numerical systems used in computer science and mathematics. Binary system represents numbers using only two digits: 0 and 1. Decimal system represents numbers using ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

To convert binary numbers to decimal numbers in Python, there are several ways to do it. Following are some of the ways:

Using int() function

The int() function in Python can be used to convert binary numbers to decimal numbers. The syntax for using int() function to convert binary numbers to decimal numbers is:

decimal_number = int(binary_number, 2)

The second argument 2 in the int() function specifies that the input binary number is in base 2.

binary_number = "1010" decimal_number = int(binary_number, 2) print(decimal_number) #Output: 10

Using the int() function and for loop

This method involves using a for loop to iterate over the binary digits and multiplying each digit with 2 raised to the power of its position. The sum of these values is the decimal equivalent of the binary number.

binary_number = "1010" decimal_number = 0 for i in range(len(binary_number)): decimal_number += int(binary_number[i]) * 2**(len(binary_number)-i-1) print(decimal_number) #Output: 10

Using the reduce() and lambda functions:

The reduce() function in Python can be used to apply a function to all the elements of a list and accumulate the result. The lambda function can be used to define the function to be applied.

from functools import reduce binary_number = "1010" decimal_number = reduce(lambda x, y: 2*x + y, [int(i) for i in binary_number]) print(decimal_number) #Output: 10

Using the int() function and bitwise operators:

This method involves using bitwise operators to convert binary numbers to decimal numbers. The left shift operator (<<) is used to shift the binary digits to the left, and the bitwise OR operator () is used to combine the shifted digits.

binary_number = "1010" decimal_number = 0 for i in binary_number: decimal_number = decimal_number << 1 if i == "1": decimal_number = decimal_number 1 print(decimal_number) #Output: 10

These are some of the ways to convert binary numbers to decimal numbers in Python. You can choose the method that works best for your particular use case.

Binary and Decimal

Binary and decimal are two number systems used to represent numerical values.


how to convert binary number to decimal number in python

Binary is a base-2 number system that uses two symbols (0 and 1) to represent values. Decimal is a base-10 number system that uses ten symbols (0-9) to represent values. Binary is commonly used in digital electronics and computing because it is easy to represent using on/off signals, and it can be used to represent all numbers and characters using a combination of binary digits. Decimal is commonly used in everyday life for counting and arithmetic, and is the default number system used in most programming languages.