💾 Archived View for hoseki.iensu.me › posts › binary-coded-decimal.gmi captured on 2023-05-24 at 17:40:48. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-01-29)
-=-=-=-=-=-=-
Like many others I'm trying to implement a GameBoy emulator. The development is sporadic to say the least and mostly occurs when I happen to have both some time and inspiration to spare. I'm still implementing the CPU instructions, and this week I came to the one called DAA (Decimal Adjust Accumulator according to the GameBoy Programming manual). I mostly wanted to summarize my findings to have something to refer back to later, but maybe this someone out there will find it useful as well.
The purpose of the DAA instruction is to correct a value which resulted from addition or subtraction of numbers in Binary Coded Decimal (BCD) representation. Since I had no idea what BCD was, I had to do some digging. Below are some notes to help me remember this for later.
In BCD representation each nibble (4 bits) represents a digit:
Decimal Binary BCD ------------------------------------------ 1 0b0000_0001 0b0000_0001 (0, 1) 10 0b0000_1010 0b0001_0000 (1, 0) 28 0b0001_1100 0b0010_1000 (2, 8)
When you operate on BCD numbers you have to convert the result into BCD as well according to the following rules:
All subtraction is achieved by adding the Two's Complement (inverse of number + 1).
Below are some examples of addition and subtraction:
0b0011_0001 + 0b0001_0001 ----------- 0b0100_0010 (BCD: 42, Binary: 66)
0b0010_1001 + 0b0001_0011 ----------- 0b0011_1100 (BCD: 3(12), Binary: 60) Correcting to BCD: 0b0011_1100 + 0b0000_0110 ----------- 0b0100_0010 (BCD: 42, Binary: 66)
Subtraction is done by adding the Two's Complement of the number being subtracted.
0b0010_1001 + 0b1110_1101 (Two's Complement of 13) ----------- 0b0001_0110 (BCD: 16, Binary: 22)
0b0010_0011 + 0b1110_0111 (Two's Complement of 19) ----------- 0b0000_1010 (BCD: 10, Binary: 10) Correcting to BCD: 0b0000_1010 + 0b1111_1010 (Two's Complement of 6) ----------- 0b0000_0100 (BCD: 4, Binary: 4)
Apparently BCD representation is often used instead of converting back-and-forth between binary and decimal when doing addition and subtraction, especially when no micro-processor is involved since the necessary circuit supposedly becomes a lot simpler. A common use-case is Seven Segment Displays where each display represents a digit. It's going to be interesting to see what GameBoy games use BCD for.
EDIT: Raul pointed out a mistake in the final calculation, thank you!
イェンス - 2022-04-11