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
Jongware
22.6k8 gold badges56 silver badges104 bronze badges
2 Answers 2
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)
answered Feb 12, 2018 at 22:48
Stefan Falk
25.8k62 gold badges227 silver badges422 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Nathan Vērzemnieks
Nice and simple, although
enumerate(reversed(binary)) is, in my opinion, more readable. (It also looks to be about 20% faster.)Stefan Falk
@NathanVērzemnieks Thank you for the hint. Going to include it in my answer :)
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)
answered Feb 12, 2018 at 22:49
Patrick Artner
51.9k10 gold badges50 silver badges79 bronze badges
Comments
lang-py
iwill corresponding to the decimal digit in the reversed order...int(binary, 2)?