I'm working on a gameboy emulator. One of the CPU operations I need to implement is the adding of a byte n to the stack pointer sp (opcode E8). The carry flag needs to be set if there is a carry from bit 7. I've looked at two implementations for this operation and they both follow the same carry detection logic. The code for this is roughly as follows:
int result = (sp + n) & 0xFFFF
boolean carry = ((sp ^ n ^ result) & 0x100) != 0
I have worked through this logic with a few examples and it does work, but I simply don't get how it works. I understand how xor works but what's the logic behind its application here? Thanks.
Addition can be written as:
a + b = a ^ b ^ (c << 1)
Where c is the carry-out for every bit (c << 1 is the carry-in). This can also be used as a way to implement addition.
Therefore if the a ^ b part is XORed out of the sum again, we're left with c << 1. Bit 8 of that is the carry-out of bit 7.