Question

I'm making a 6502 emulator (and after that I'll emulate the other NES components around it to have a fully functional NES emulator) and I came across the branch-on-condition instruction (relative). Now, what I'm wondering about is, is the byte considered to be saved as two's complement, or as a regular negative byte? Here's what I mean:

In one of the 6502 documents (unofficial of course) it gives this example:

BEQ $A7 ;Branch-on-equal with value 0xA7
$F0 $A7 ;Translation into hex

In the document, it says that 0xA7 should be taken as -39, and is represented like this:

1 0 1 0 0 1 1 1 ;-39 dec

If the 7th bith (starting from 0) would be a 0, it would just be 39:

0 0 1 0 0 1 1 1 ;39 dec

I'm wondering, is this document correct, or am I supposed to be using two's complement, meaning that:

1 0 1 0 0 1 1 1 

would actually be -89?

I'm asking this because I'm programming the emulator in Java, and bytes are interpreted in two's complement, and I've been seeing it that way in a lot of instructions, and now I'm being struck with confusion.

Was it helpful?

Solution

Wow, set the way-back machine on this one! I used to program in assembly on the '02 family for years back in the 70's and 80's on the Atari VCS, computer family and coin-op arcade games. Ok, as I recall all the BEQ (branch on equal) instruction does is check the status of the 'zero flag' and branch if it is set. The zero flag gets set/cleared based on comparison and math functions.

Since you are asking about +/- numbers on the '02, you probably want BPL (branch if plus) or BMI (branch if minus) which are based on the sign 'N' flag which is essentially just bit 7 of the accumulator. So decrementing 0 would get you $ff and set the minus 'N' flag. You would interpret this $ff as -1, meaning 2's complement.

Update: Yes, I was perhaps a little round-about in my answer.. So, yes it is 2's complement, and the offset is as of the address of the next opcode that will be fetched, meaning -2 or $fe would get you back to your 'BEQ'. So $F0 $A7 would in fact branch backwards 89 bytes from the address 2 bytes ahead of the address of your BEQ

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top