Advertisement
Guest User

Untitled

a guest
Jun 30th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. import math
  2. #Input
  3. num = input("Enter a whole number: ")
  4.  
  5. #Floors input in case of a non whole number
  6. decimal = math.floor(float(num))
  7.  
  8. #Variables
  9. exp = 0
  10. divTwo = 1
  11. zeros = 0
  12. total = ""
  13. if decimal < 0:
  14. total += str('-')
  15. decimal = -decimal
  16. if decimal == 0:
  17. total = str('0')
  18. else:
  19. #Loops while remainder is > 0.
  20. while int(decimal) > 0:
  21.  
  22. #Increases exponent by one if 2^exp is less than or equal to the remainder.
  23. if 2 ** exp <= int(decimal):
  24. exp += 1
  25.  
  26. else: #Multiplies 2 by the exponent and places zeros in between 1s. Also subtracts from the exponent.
  27. exp -= 1
  28.  
  29. #Determines whether or not to subtract from the remainder and add a '1' to the binary translation or just add a '0' to the binary translation.
  30. if 2 ** exp <= int(decimal):
  31.  
  32. #Counts how many zeros need to be added to the end of the binary translation.
  33. if 2 ** exp == int(decimal):
  34. divTwo = int(decimal)
  35.  
  36. #Loops until all remaining zeros have been accounted for.
  37. while divTwo > 1:
  38. divTwo = divTwo / 2
  39. zeros += 1
  40.  
  41. decimal = int(decimal)
  42. decimal -= 2 ** exp
  43. total += str('1')
  44.  
  45. else:
  46. total += str('0')
  47.  
  48. #Places remaining zeros.
  49. while zeros > 0:
  50. total += str('0')
  51. zeros -= 1
  52.  
  53.  
  54. #Displays answer.
  55. print ('Binary: ' + total)
  56. input()
  57.  
  58. #
  59. #
  60. #Or 'bin(decimal)' works too, but this was for fun
  61. #
  62. #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement