Advertisement
scorpion2018

Binary to Decimal Conversion

Nov 17th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. '''How to read a number from the user and convert to decimal'''
  2.  
  3. '''Ask user to enter an 8 digit binary number'''
  4. import sys
  5. binary = input ("please enter an 8 digit binary number: ")
  6.  
  7. '''Checking for binary length'''
  8. if len(binary)>8 or len(binary)<8:
  9. print ('Please enter an 8-bit binary number')
  10. sys.exit
  11.  
  12. # checking for valid binary digits
  13. d = 0
  14. count = 0
  15. for d in binary:
  16. if d =='0' or d == '1':
  17. continue
  18. else:
  19. print('Binary number must contain combinations of 1s and 0s.' )
  20. sys.exit()
  21.  
  22.  
  23. # converting binary to decimal
  24. d = 0
  25. count = 0
  26.  
  27. for b in binary:
  28. d = d + int (b) * (2 ** count)
  29. count = count + 1
  30.  
  31. # displaying the equivalent decimal number
  32. print('The decimal equivalent of the binary number is: ' (d))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement