title: Overflow and Carry flags on Z80
body: <p>I have gotten round to implementing the ADD A,r set of opcodes on my Z80 core. I had a bit of confusion about the carry and overflow flags which I think I've nailed, but I wanted to put it to the community to check that I'm right.</p>
  
  <p>Basically, from what I can see, the ALU in the Z80 doesn't care about signed/unsigned operations, it just adds bits. This means that if two 8-bit values are added together and cause a 9-bit value as a result of their addition, the carry flag will be set. This includes adding two negative two's complement numbers, for example -20 (11101100) and -40 (11011000), as although the result is -60 (11000100), the result is actually a 9-bit value 1 1100 0100. This surely means if adding two negative two's complement values, the carry flag will always be set, even when there is no overflow condition - am I right?</p>
  
  <p>Secondly, I decided that to detect an overflow in this instruction, I would XOR bit 7 of both operands, and if the result was 10000000, then there is definitely no overflow - if the result of this is 00000000 then there could be an overflow as the signs are the same, and I would therefore XOR bit 7 of the result of the addition with bit 7 of either operand, and if the result of this is 10000000 then an overflow has occurred and I set the P/V overflow flag. Am I right here also?</p>
  
  <p>Sorry for such a convoluted question, I'm pretty sure I'm right but I need to know before I carry on with countless more instructions based on this logic. Many thanks.</p>