Skip to content
systemcoding.dev
Virtualization

Store a BCD number with the CHIP-8 FX33 instruction

FX33 splits V[X] into hundreds, tens and ones and stores them at I, I+1 and I+2. It leaves I unchanged, which is easy to get wrong in an emulator.

1 min read
Summarize in AI

CHIP-8 has no decimal printing, so games that show a score call FX33 to turn a byte into three digits and then look up each digit's font sprite. It is two divisions and a modulo.

c
case 0x33: {
    uint8_t v = V[x];
    mem[I]     = v / 100;
    mem[I + 1] = (v / 10) % 10;
    mem[I + 2] = v % 10;
    break;
}

For V[x] = 254 and I = 0x300, the three bytes at 0x300 become:

Text
mem[0x300..0x302] = 2 5 4

Each value is a digit from 0 to 9, not an ASCII character, and the font set in memory is addressed with FX29, which multiplies the digit by 5 because each built-in glyph is five bytes tall. A typical score routine runs FX33, loads the three digits back with FX65, and then draws each one.

The instruction does not move I. After it runs, I still points at the first digit, so a following FX65 reads them straight away. Emulators that add 3 to I by mistake print garbage numbers on the second call. Behaviour of the related FX55 and FX65 differs between the original interpreter and later ones, but FX33 is the same on all of them, per the CHIP-8 technical reference.

Also inHardware
Taggedc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.