Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the behavior of the carry flag for CP on a Game Boy?

Tags:

z80

gameboy

On the page 87 of the Game Boy CPU Manual it is claimed that the CP n instruction sets the carry flag when there was no borrow and that it means that A < n. This seems to conflict itself, because the carry flag is set when A > n.

An example: If A=0 and B=1, CP B sets the flags like SUB A, B, which is 0 - 1. This becomes 0 + 255 = 255 and the carry flag is not set, even though A < B.

I came across this same issue in other Z80 documents as well, so I don't believe this is a typo.

Am I misunderstanding how borrow and SUB work or is there something else going on? Is SUB not equal to ADD with two's complement in terms of flags?

like image 659
Hassedev Avatar asked Jul 14 '15 14:07

Hassedev


People also ask

What does the carry flag do?

The carry flag enables numbers larger than a single ALU width to be added/subtracted by carrying (adding) a binary digit from a partial addition/subtraction to the least significant bit position of a more significant word.

How do you check half carry?

Summarizing, if the result of a binary addition contains a non-decimal low digit or causes the half-carry flag to be set, the result must be corrected by adding 0616 to it; if the result contains a non-decimal high digit, the result must be further corrected by adding 6016 to produce the correct final BCD value.


1 Answers

The GameBoy CPU manual has it backwards. SUB, SBC and CP all set the carry flag when there is borrow. If SUB/SBC/CP A,n is executed then carry is set if n > A otherwise it is clear.

This is consistent with Z-80 (and 8080) operation. As well MAME and MESS implement carry the same way.

like image 66
George Phillips Avatar answered Oct 01 '22 18:10

George Phillips