Z80 assembly: Checksums
Add the bytes in a block to make a simple checksum.
A checksum is a short value calculated from a block of data. This example adds three bytes. It wraps at 255 because A is 8 bits. A receiver can calculate the sum again and compare it with the stored checksum.
The result is stored in A. The loop reads each byte once. The value is 12h + 34h + 56h = 9Ch, or 156 decimal.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
HL points to the first byte. B counts the three bytes. Each loop pass adds one byte to A and moves HL forward.
Registers and data
Flags
A contains the running sum. HL points to the next byte. B counts bytes left. The checksum uses 8-bit arithmetic, so sums above 255 wrap around.
Data block
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
What a simple sum can detect
| Data change | Sum result |
|---|---|
| Change one byte by +1 | Usually changes the checksum by +1 |
| Swap two bytes | Checksum stays the same |
| One byte +1 and another −1 | Checksum stays the same |
This sum can detect some errors. It cannot detect every change. Stronger checks use a wider checksum or a CRC.
This is an 8-bit additive checksum with no stored checksum byte. It is for learning, not secure data validation.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Sets up the data pointer, counter and sum. |
| ADD | Add | Adds the current byte to A. |
| INC | Increment | Moves HL to the next byte. |
| DJNZ | Decrement B and Jump if Not Zero | Repeats the loop three times. |
| DB | Define Byte | Assembler directive. Defines the data block. |
| HALT | Halt | Stops after the checksum is ready. |