Branch Operations

This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade.
View original topic
Branch Operations
by on (#70459)
Code:
0200:   A9 00      START:   LDA #0
0202:   85 00               STA PILEN
0204:   18                  CLC
0205:   20 00 01   NXKEY:   JSR GETKEY
0208:   C9 0F               CMP #15
020A:   D0 05               BNE NXTST
020C:   20 87 02            JSR BEEP3
020F:   90 EF               BCC START
0211:   C9 0E      NXTST:   CMP #14


The part that has me confused is line 6. BNE's opcode is D0 so no problem there, but what has me confused is the 05 following. By my math, it is coming up one short of NXTST. However, I'm thinking that when the CPU reads the '05' it then moves onto the next slot before counting? Would that be the case?

Also, with BCC START, given START's position, you would get 02FF (or 0300 if current address is incremented by one after reading EF) and if START is at 0200, how exactly does that work? I'm thinking it kind of just rolls over back to 0200 instead of going to 0300.
Re: Branch Operations
by on (#70461)
67726e wrote:
However, I'm thinking that when the CPU reads the '05' it then moves onto the next slot before counting? Would that be the case?


Exactly correct. It adds 5 to the PC, but then the normal "next byte of instruction stream" incrementer still fires too.

Quote:
I'm thinking it kind of just rolls over back to 0200 instead of going to 0300.


No; for relative jumps this number $EF is actually a signed 8-bit number, or -17.

by on (#70462)
As long as you remember that the relative operand is applied using the location of the next instruction's opcode as the starting point, you should not be confused.

by on (#70493)
doppelganger wrote:
As long as you remember that the relative operand is applied using the location of the next instruction's opcode as the starting point, you should not be confused.


6502 Branching Explanation (I was away for a long while, so I might not have it right: Please correct me, if I'm wrong!):

If Brancharray $00-$7f, CodeNum_Add
If Brancharray $80-$FF, CodeNum_Subtract

If you need more info, Check out any one of the 6502 opcode documents in the internet, There is a couple on this site, Although I'd get it from:
http://www.Zophar.net (Zophar's Domain, Documents section)
or http://www.RomHacking.Net (RHDN)

by on (#70494)
Even simpler:
1. Read opcode, increment PC, read second byte as unsigned 8-bit value, increment PC. This takes two cycles.
2. If branch condition is false, do nothing more.
3. Flip high bit of second byte (XOR with $80), add to PC, then subtract $80. Also add an extra cycle.
4. If high 8 bits of PC are different than they were at step 2, add a fourth cycle.