Quick Post: Printing binary numbers in Commodore BASIC 2.0
By Michael Doornbos
- 2 minutes read - 247 wordsCommodore BASIC 2.0
A lot of fun with binary numbers can be had by printing them to the screen. This is a quick post to show how to do that with Commodore BASIC 2.0. This is a follow up to Quick Post: XOR in Commodore BASIC 2.0.
We’ll be using both of these in upcoming posts, so it’s good to have them handy.
5 REM PRINT ALL 8 BIT NUMBERS IN BINARY
10 FOR N= 0 TO 255
20 FORI=7 TO 0 STEP-1
25 B=0
30 IF N AND 2^I THEN B=1
40 PRINTMID$(STR$(B),2);
50 NEXT
60 PRINTN
70 NEXT
This prints all the numbers from 0 to 255 in binary. It’s a little slow, but it’s easy to understand and fun to watch.
The key lines here are:
20
- This is a loop that counts from 7 to 0. This is the 8 bits of the number.
30
- This checks if the bit is set. If it is, it sets B to 1.
40
- This prints the bit. It’s a little tricky. We’re converting the number to a string, and then taking the second character. This is because the string is " 1" or " 0", and we want to get rid of the space that Commodore BASIC always prints at the beginning of a number.
Note that the ^ in the code block is actually the up arrow character on the Commodore . It’s not the caret character.
That’s it. Happy hacking!