title: Gameboy emulator - carry and half-carry flag
body: <p>I'm working on a GameBoy emulator in C and currently I'm working on the CPU core. Nevertheless, I am not sure if I understand when the carry and half-carry flags are set, especially in operations like:</p>
  
  <pre><code>LD HL, SP+n
  </code></pre>
  
  <p>(<a href="http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html" rel="nofollow">http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html</a>)</p>
  
  <p>My implementation of this opcode is:</p>
  
  <pre><code>DELETED
  </code></pre>
  
  <p>Is it correct implementation or did I misunderstand flags?</p>
  
  <p>EDIT:
  My implementation was wrong and this question duplicates another.
  Here is the correct implementation (I hope), it probably isn't very resource effective though:</p>
  
  <pre><code>case 0xF8:
  {
          int8_t n = (int8_t)readmem(PC+1); /* Load n and use it as signed integer */
          /* HL and SP are declared as uint16_t */
          HL = SP + n; /* Put the value of SP + n to 16-bit register HL*/
          resetf(FZ); /* Reset zero flag*/
          resetf(FN); /* Reset subtract flag*/
          if((SP &amp; 0x000F + n &amp; 0x000F) &amp; 0x00F0)
          {
              setf(FH); /* Set half-carry flag */
          }
          else
          {
              resetf(FH); /* Reset half-carry flag */
          }
          if((SP &amp; 0x00FF + n &amp; 0x00FF) &amp; 0x0F00)
          {
              setf(FC); /* Set carry flag */
          }
          else
          {
              resetf(FC); /* Reset carry flag */
          }
          PC+=2; /* Increase program counter */
  break;
  }
  </code></pre>