DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   qbasic (http://www.daniweb.com/code/qbasic.html)
-   -   Decimal to Binary (qbasic/BCX) (http://www.daniweb.com/code/snippet153.html)

vegaseat qbasic syntax
Jan 16th, 2005
One more look at BCX basic code to show the qbasic programmers how they can modernize. This shows a function that converts an integer value to a binary string. Notice that with BCX basic you need to declare your variables. Makes the code a little easier to read too. Variable, Function and Sub names are case sensitive, keywords are not.

  1. ' converting a decimal integer to a binary string
  2. ' BCX basic
  3. '
  4.  
  5. '
  6. ' postfix $ indicates a string variable
  7. ' could be written as: dim A as String
  8. '
  9. DIM A$
  10.  
  11.  
  12. A$ = dec2bin$(123)
  13. PRINT "decimal 123 = binary ", A$
  14.  
  15. A$ = dec2bin$(255)
  16. PRINT "decimal 255 = binary ", A$
  17.  
  18. pause ' wait
  19.  
  20.  
  21. '
  22. ' postfix $ in function name indicates that the function returns a string
  23. ' could be written as: function dec2bin Optional (a, digits=0) as String
  24. ' keyword Optional indicates parameter digits is optional and defaults to 0
  25. ' variables declared within the function are local
  26. '
  27. FUNCTION dec2bin$ Optional (a, digits=0)
  28. DIM k, tmp, t ' default to integer variables
  29. DIM T$ ' string variable
  30.  
  31. ' don't know the number of digits in a, so figure it out
  32. IF digits = 0 THEN
  33. tmp = a
  34. WHILE tmp > 0
  35. tmp = tmp >> 1 ' shift right by 1 place
  36. digits++ ' increment by 1, same as: digits = digits + 1
  37. WEND
  38. END IF
  39.  
  40. t = 1
  41.  
  42. ' do the conversion to zeros and ones
  43. FOR k = 1 TO digits
  44. tmp = a AND t
  45. IF tmp = 0 THEN
  46. T$ = "0" & T$
  47. ELSE
  48. T$ = "1" & T$
  49. END IF
  50. t = t << 1 ' shift left by 1 place
  51. NEXT
  52.  
  53. FUNCTION = T$ ' result is in T$, return this
  54. END FUNCTION
  55.