Relative Addressing

From NES Hacker Wiki
Jump to: navigation, search

Relative Addressing is used on the various Branch-On-Condition instructions. A 1 byte signed operand is added to the program counter, and the program continues execution from the new address. Because this value is signed, values #00-#7F are positive, and values #FF-#80 are negative.

Keep in mind that the program counter will be set to the address after the branch instruction, so take this into account when calculating your new position.

Since branching works by checking a relevant status bit, make sure it is set to the proper value prior to calling the branch instruction. This is usually done with a CMP instruction.

If you need to move the program counter to a location greater or less than 127 bytes away from the current location, make a nearby JMP instruction, and move the program counter to the JMP line.


This example creates a countdown loop. Memory address $50 is loaded with #10, and then decreased. We then check if the Zero Flag has been set, which will only occur when we decrease all the way down to 0. If we haven't reached zero, we go back to $0005 and decrease it again. If we have hit 0, we jump past the line that would send us back up, escaping the loop.

0001:A9 01     LDA #$10        ; Loads A with #10.
0003:85 50     STA $0050       ; Stores A into $0050.
0005:C6 50     DEC $0050       ; Decrement $0050.
0007:D0 08     BEQ $04         ; If the Zero Flag is set, JMP from our current location ($09), 
                                 plus the operand ($04) to the address $000C.
0009:4C 05 00  JMP $0005       ; Jump back to $0005, creating a countdown loop.
000C:00        BRK             ; Done.


The following opcodes support relative addressing: