Calculating Branches
I have just started programming my VIC-20 with machine language. I don't have an assembler/monitor and I don't know how to calculate the offset for branch instructions. Could you please clear this up for me?
Keith Stout
The "offset" branches you've asked about (which include BCC, BCS, BEQ, BMI, BNE, BPL, BVC, and BVS) are easily calculated. The format for the commands is OPERAND / OFFSET, where OPERAND is the desired branch command (BEQ, BNE, etc.) and OFFSET is a single-byte value.
Whether branching forward or backward, the offset is calculated by counting from the next byte after the offset byte of the branch instruction. For an example, take a look at the following program sample.
1000 LDA $C000 1003 STA $FB 1005 CMP #$FF 1007 BNE $1000 1009 BEQ $1011 100B JSR $2000 100E JSR $3000 1011 RTS
The branch (BNE) at address 1007 is calculated by counting backward starting at address 1009 (the byte following the offset value). In this case, the offset value would be 256-9 or 247. Backward branches are calculated by subtracting the offset value from 256. The forward branch (BEQ) at address 1009 is accomplished by counting forward from byte 100B. In this case, the offset byte's value is 6.
Because the offset type of branch instruction uses a single byte for the offset value, the distance you can branch within the program is limited to 128 bytes backward and 127 bytes forward.