Half carry flag emulating the GBA

491 Views Asked by At

I've seen some documentation on detecting the HALF CARRY flag changes for the GBA. I'm writing an emulator in C++ and i'm having a hard time thinking on how to detect HALF CARRY flag changes when i'm subtracting two different numbers. (This should be apparent also in shift and rotate operations, ADD has been well documented here on Stack Overflow and on different guides).

So far, I have this function that detects if an operation triggers the HALF CARRY to be set (I'm positive this works only with addition):

#include <stdint.h>
static constexpr bool HalfCarryOnAddition(uint8_t first_num, uint8_t second_num)
{
    return (((first_num & 0xF) + (second_num & 0xF)) & 0x10) == 0x10;
}

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

I understand now what half carry essentially is -> Its a check for the carry bit on HALF of the size of the type you're looking for.

The implementations for ADD, SUB for the HALF-CARRY flags for both uint8_t and uint16_t is:

#include <stdint.h>
static constexpr bool HalfCarryOnAddition(uint8_t first_num, uint8_t second_num)
{
    return (((first_num & 0x0F) + (second_num & 0x0F)) & 0x10) == 0x10;
}

static constexpr bool HalfCarryOnAddition(uint16_t first_num, uint16_t second_num)
{
    return (((first_num & 0x00FF) + (second_num & 0x00FF)) & 0x0100) == 0x0100;
}

static constexpr bool HalfCarryOnSubtration(uint8_t first_num, uint8_t second_num)
{
    return (int)(first_num & 0x0F) - (int)(second_num & 0x0F) < 0;
}

static constexpr bool HalfCarryOnSubtration(uint16_t first_num, uint16_t second_num)
{
    return (int)(first_num & 0x00FF) - (int)(second_num & 0x00FF) < 0;
}