2

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
asked Feb 12, 2018 at 22:41
4
  • 1
    The problem is that i will corresponding to the decimal digit in the reversed order... Commented Feb 12, 2018 at 22:46
  • I suppose that your assignment doesn't let you use int(binary, 2)? Commented Feb 12, 2018 at 22:51
  • @dan04 yes, we were told not use that Commented Feb 12, 2018 at 22:53
  • @usr2564301 no, i just needed it for python 3, sorry for tagging python 2.7 Commented Feb 12, 2018 at 22:56

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice and simple, although enumerate(reversed(binary)) is, in my opinion, more readable. (It also looks to be about 20% faster.)
@NathanVērzemnieks Thank you for the hint. Going to include it in my answer :)
2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.