Rahul Vashishtha
Rahul Vashishtha

Reputation: 1

Converting binary number to decimal number using list

I have tried this code multiple times. But I'm always getting the output as 45, which is wrong.

a = [1, 0, 1, 1]
value = 0
a.reverse()
print(a)             #reversed list
for i in a:
    if i==1:
        for x in range(0,len(a)):
            value += pow(2,x)
    else:
        continue
print("decimal value of binary number is:",value)

Upvotes: 0

Views: 137

Answers (4)

When converting the list to a string, one can use the int function:

int("".join(map(str,a[::-1])), base=2)

Upvotes: 0

Leo Arad
Leo Arad

Reputation: 4472

This code will convert you the list to a decimal number.

a=[1,0,1,1]
value=0
for i, v in enumerate(a):
    value += pow(2, i) * v

print("decimal value of binary number is:",value)

Output

decimal value of binary number is: 13

Upvotes: 0

ptrstr
ptrstr

Reputation: 56

You should look into bitwise operations. It'll make this more efficient and is best practice when dealing with bits. There's also more Pythonic ways to achieve this (using int(x, 2) for example.) With bitwise operations it would look like this:

for i in a:
    value |= i
    value <<= 1
value >>= 1

Upvotes: 1

Simon A
Simon A

Reputation: 221

Everytime you detect a 1, you add 2^3 + 2^2 + 2^1 + 2^0 = 15, and you do this 3 times which is why you get 45. You should be doing this :

a=[1,0,1,1]
value=0
a.reverse()
print(a)             #reversed list
for pos, i in enumerate(a):
    if i==1:
        value += 2**pos
    else:
        continue
print("decimal value of binary number is:",value)

Upvotes: 0

Related Questions