johnpentyrch

ex311

Feb 26th, 2022 (edited)
652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. ##Reads a whole number (an integer) in base 10 and converts it to binary
  2. decin='xx' #to force initial read of number
  3. while not(decin.isnumeric()): #looks while invalid (nn numeric input)
  4.     decin=input('enter a denary number to convert (whole number) ')
  5.     decin=decin.strip() #strip leading and trailing spaces
  6.    
  7. cfwd=int(decin)  #copy the number and convert to integer
  8. if (cfwd==0):
  9.     binaryout="0" #case of a 0 input
  10. else:
  11.     binaryout=""  #set initial string to blank
  12. while (cfwd!=0): #loop while there are bits to process
  13.     remain=cfwd%2 #get the remainder to give next bit
  14.     binaryout=str(remain) + binaryout #prepend that bit as a character to output string
  15.     cfwd=cfwd//2 #float divide for next binary digit position
  16.  
  17. print( "The value of denary ", decin, " in binary is ", binaryout)
  18.  
Add Comment
Please, Sign In to add comment