2
votes

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.

1
There is some discussion of this here: forums.nesdev.com/viewtopic.php?t=102. The conclusion seems to be that it's wrong; it should be 2's complement.Oliver Charlesworth
I don't know a lot about processors, but I read before that a CPU can easily keep track of binary numbers by using two's complement, which is why I asked this question. For a second I was about to delete it, thinking that the document was made by very experienced people i.e. unlikely to be incorrect, but luckily I didn't or else my whole CPU would be worthless. Thanks. Ironically I had also noticed the duplicate 0x60 opcode mistake, which is why I (luckily) use multiple resources as references. It seems that even the best are easily prone to error.ZimZim
Great project to undertake. Good luck. :)alex

1 Answers

3
votes

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