Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Game Boy: What constitutes a "half-carry"?

The Game Boy Z80 CPU has a half-carry flag, and I can't seem to find much information about when to set/clear it.

What I understand so far is that any 8-bit add, subtract, shift, or rotate operation (and maybe others?) set it to bit 4 of the result(?), and the DAA instruction sets/uses this somehow. What I'm not sure is how 16-bit instructions affect it and whether it's affected or not by the use of certain registers.

like image 686
Rena Avatar asked Jan 15 '12 08:01

Rena


People also ask

What is the purpose of Zero flag?

Along with a carry flag, a sign flag and an overflow flag, the zero flag is used to check the result of an arithmetic operation, including bitwise logical instructions. It is set to 1, or true, if an arithmetic result is zero, and reset otherwise.

What does the carry flag do?

What Does Carry Flag (C Flag) Mean? A carry flag in computer science works with the arithmetic logic unit (ALU) of a computer's central processing unit to handle arithmetic and bitwise logical operations on binary numbers. The carry flag is used when an operation changes the left-hand bit of the binary system.

What does a half carry?

It indicates when a carry or borrow has been generated out of the least significant four bits of the accumulator register following the execution of an arithmetic instruction. It is primarily used in decimal (BCD) arithmetic instructions.

How do you determine half carry?

The variables a and b are both being bitwise ANDed wth 0xf and then added together. Then we can simply check if that sum & 0x10 == 0x10: if sum & 0x10 == 0x10 { // a half-carry occured. }


1 Answers

It's the carry from bit 3 to bit 4, just like the normal carry flag records carry from bit 7. So, e.g. to get the half carry bit in an add:

((a&0xf) + (value&0xf))&0x10 

Which gives 0x10 if half carry should be set, 0 otherwise. Getting half carry from the other relevant ops follows naturally - the questions is whether there was carry from the low nibble to the high.

To put things in perspective, the z80 has a 4bit ALU and performs 8bit ops by doing two 4bit ops. So it gets half carry very naturally, as an intermediate result.

DAA is interested in the flag because if half carry is set then two digits that add up to more than 16 were added in the low nibble; that will have correctly produced carry into the upper nibble but will have left the low nibble 6 lower than it should be, since there were six more values between 10, when it should have generated carry, and 16, when it did.

like image 78
Tommy Avatar answered Oct 01 '22 20:10

Tommy