what is the best code for counting in machine language on the Commodore 64?
- User
what is the best code for counting in machine language on the Commodore 64?
- Assistant
what is the best code for counting in machine language on the Commodore 64?
Counting in machine language on the Commodore 64 typically means incrementing a value stored in memory or a register and looping through a sequence. The "best" code depends on what exactly you want to count (e.g., counting up to a number, counting down, counting with output to the screen, etc.). Below is a simple, minimal example of a loop in 6502 assembly (the CPU of the C64) that counts from 0 to 9 and stores the result in a memory location.
This example increments the value in a memory location named counter from 0 to 9 and then stops.
*= $0801 ; Start at $0801, typical start address for a program on the C64
LDX #$00 ; X register = 0 (our counter)
loop:
STX counter ; Store X into the memory location "counter"
INX ; Increment X
CPX #$0A ; Compare X with 10 (decimal)
BNE loop ; If X != 10, branch back to loop
RTS ; Return from subroutine (ends program if called as such)
counter: .byte 0 ; Memory location to hold our counter
LDX #$00 initializes the X register to zero.loop: is a label.STX counter stores the current X register value to counter.INX increments X.CPX #$0A compares X to 10 decimal.BNE loop branches back if X is not equal to 10.RTS ends the program (in a standalone program on C64, you usually end with a JMP or similar, but here RTS is standard in subroutines)..byte 0 reserves one byte for the counter.If you write this in a 6502 assembler (or an emulator with assembler built in), assemble it at 0801 decimal).
Counting values into memory is one thing; if you want to output the count to the screen, you'll need to convert the binary count to ASCII and write to screen memory at $0400.
Here is a small snippet to display the count from 0 to 9 on the first screen position:
*= $0801
LDX #$00 ; start counter at 0
loop:
TXA ; transfer X to A
CLC ; clear carry for ADC
ADC #$30 ; convert 0-9 to ASCII ('0' = $30)
STA $0400 ; store character at screen memory $0400
TXA ; recover X from A lost due to ADC
INX ; increment counter
CPX #$0A ; check if count < 10
BNE loop ; loop if not equal
RTS
If you'd like a complete assembled program for the C64 including proper start and exit routines or a counting routine with output, please let me know!
Not yet included in a published release.