JetYT

QBasic binary to decimal

Sep 13th, 2019
643
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. DIM BITS AS INTEGER ' Define total amount of bits in the byte
  2.  
  3. BITS = 16 ' Define amount of bits to allocate to binary
  4.  
  5. DIM BYTE1(BITS) AS INTEGER ' BITS-allocated byte
  6. DIM DECIM AS LONG ' Standard output byte as decimal (after translation)
  7.  
  8.  
  9. RETRY: ' Retry in case user inputs incorrect number
  10. PRINT "Please enter a valid number between 0 and" + STR$((2 ^ BITS) - 1); ' First prompt w/ evaluation of highest possible input number
  11. INPUT "> ", DECIM ' Ask for user input with second prompt and pass data into DECIM LONG (dimmed previously)
  12. IF DECIM > (2 ^ BITS) - 1 THEN ' Incase user inputs number higher than highest possible input number
  13.     COLOR 12 ' Display message in red for error
  14.     PRINT "Number cannot be over" + STR$((2 ^ BITS) - 1) + "!" ' Display number overflow error
  15.     COLOR 7 ' Return to standard color
  16.     GOTO RETRY ' Go back to retry prompting
  17. ELSEIF DECIM < 0 THEN 'Incase user inputs a negative number
  18.     COLOR 12 ' Display message in red for error
  19.     PRINT "Number cannot be under 0!" ' Display number underflow error
  20.     COLOR 7 ' Return to standard color
  21.     GOTO RETRY ' Go back to retry prompting
  22. END IF ' End input check if statement
  23.  
  24. FOR X = 1 TO BITS ' Declare all bits in byte as empty
  25.     BYTE1(X) = 0 ' Empty bit
  26. NEXT X ' End for loop
  27.  
  28. ' --- MAIN ALGORITHM CODE EXECUTION HERE ---
  29. ' Since binary is calculated from
  30. ' the highest value to the lowest
  31. ' we need to create a for loop that
  32. ' counts from the highest bit to the lowest
  33. ' This allows the program to loop until all
  34. ' bits have been processed and to make sure that
  35. ' the toggled bits are positioned correctly
  36.  
  37. X = BITS ' Set X to BITS to start loop at TOP
  38. FOR Y = 1 TO BITS ' Begin for loop to declare all bits in byte
  39.     X = X - 1 ' Decrease X by one to down the binary chain
  40.     MODULO = 2 ^ (X) ' Convert bit position into a base-10 decimal number
  41.     IF MODULO <= DECIM THEN ' Is the current decimal number able to be subtracted by the converted bit position?
  42.         BYTE1(X) = 1 ' If so, set that bit position to 1
  43.         DECIM = DECIM - MODULO ' Take away converted bit position from the decimal number
  44.     ELSE ' If not
  45.         BYTE1(X) = 0 ' Set that bit position to 0
  46.     END IF ' End if statement so as to continue the loop
  47.     PRINT ((BYTE1(X))); ' Print that result on screen
  48. NEXT Y ' End bit declaration for loop
  49. PRINT ' Create blankline
RAW Paste Data