Home > Back-end >  How can I correctly convert binary characters in list to decimal
How can I correctly convert binary characters in list to decimal

Time:03-06

I want to create a function which will convert the binary numbers in list array to the decimal numbers. For that I have reversed a list and used for loop to iterate the list items. However I am unable to get correct result. Can anyone help me where am I committing the mistake?

def binary_array_to_number(arr):
     #arr = arr.reverse()
    arr = arr [::-1] 
    new_num = 0
    for item in arr:
        for i in range(len(arr)):
            new_num = new_num item*(2**i)
    print(new_num)
binary_array_to_number(arr= [0, 0, 0, 1])

CodePudding user response:

Python has built-in conversion from binary to base-10 numbers using the int() constructor. By converting the array to a string representing the binary number, you can use int to convert it to decimal:

binary_arr = [0, 0, 0, 1]
binary_string = ''.join(str(digit) for digit in binary_arr)  # this line simply converts the array to a string representing the binary number [0, 0, 0, 1] -> '0001'
decimal_number = int(binary_string, 2)  # the 2 here represents the base for the number - base 2 means binary.
print(decimal_number)  # prints '1'

CodePudding user response:

You're not checking if the current bit is 1 or not, so you'll always generate 2**n - 1. Also, you've got two loops running instead of one, which will also lead to an incorrect result.

def binary_array_to_number(arr):
     #arr = arr.reverse()
    arr = arr [::-1] 
    new_num = 0
    for i in range(len(arr)):
        if arr[i]:
            new_num  = (2**i)
    print(new_num)
binary_array_to_number(arr= [0, 1, 0, 1])
  • Related