I came across some code today for converting binary to decimal, and I realised that I don't fully understand how it works.

Here it is in Python:

#Binary to denary conversion  
binary = input("Input a number in binary:")  
denary = 0  
for digit in binary:  
  # A left shift in binary means x2  
  denary = denary * 2 + int(digit) 
print("Your denary number is: " + str(denary))

To help myself understand it I tried "converting" from base 10 to base 10. E.g.

For 246:

d = 0
d *= 10, d += 2, d = 2
d *= 10, d += 4, d = 24
d *= 10, d += 6, d= 246

I'm having trouble seeing how this works for binary to decimal though. Could someone please give me a clear explanation that's thorough and easy to follow?

  • $\begingroup$ This doesn't actually translate binary to decimal. It translates a string assumed to contain 0's and 1's to a number. The number is then printed using a function printing numbers in decimal format. $\endgroup$ – gnasher729 Oct 20 at 20:12
  • $\begingroup$ As gnasher729 noted, this algorithm just translates the ASCII sequence of characters '1' and '0', where '1' becomes a set bit and '0' becomes an unset bit at the corresponding positions, since it starts from the most significant bit and multiplication by 2 is the same as a shifting all bits one position to the left and inserting an unset bit on the right side. For the record, Python has a better way to do that: "denary = int(binary, 2)". The actual 'magic' of translating binary representation to decimal happens inside of "str(denary)" $\endgroup$ – ZyTelevan Oct 20 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.