armallah
armallah

Reputation: 101

Binary to Decimal For Loop

Hi I am a new programmer and I trying to complete one my assignments which requires to me convert a binary number to a denary one. I am not getting any errors however i dont get the correct denary equivalent, please help. This is what i've done so far.

binary = "10111"
denary = 0
length=len(binary)
for i in range(length-1,-1,-1):
   if binary[i] == "1":
    denary += (2**i)
else:
    denary += 0
print(denary)

and the output is:

29

Upvotes: 2

Views: 3076

Answers (2)

Stefan Falk
Stefan Falk

Reputation: 25457

You're coming from the wrong direction. You can use binary[::-1] or reversed(binary) to reverse the array.

binary = "10111"
denary = 0

for i, d in enumerate(reversed(binary)):
    if d == "1":
        denary += (2**i)

print(denary)

Also note that you can do this:

denary = int(binary, 2)  # Parses string on base 2 to integer base 10

print(denary)

Upvotes: 4

Patrick Artner
Patrick Artner

Reputation: 51683

You can use a reverse list like this:

binary = "10111" # needs to be reversed so the lowest bit is in front for ease of computing
denary = 0

# ind = index,  bit = the bitvalue as string of the reversed string 
for ind, bit in enumerate(binary[::-1]): # reversed copy of string
    denary += int(bit)*2**ind  # if bit is 0 this evaluates to 0, else to the  power of 2
print(denary)

Upvotes: 2

Related Questions