← r0mheat z80 lessons: all projects

Z80 assembly: Checksums

Add the bytes in a block to make a simple checksum.

ADD · INC · DJNZ

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.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

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

#AddressInstructionResultT-states

What a simple sum can detect

Data changeSum result
Change one byte by +1Usually changes the checksum by +1
Swap two bytesChecksum stays the same
One byte +1 and another −1Checksum 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
NameStands forMeaning here
LDLoadSets up the data pointer, counter and sum.
ADDAddAdds the current byte to A.
INCIncrementMoves HL to the next byte.
DJNZDecrement B and Jump if Not ZeroRepeats the loop three times.
DBDefine ByteAssembler directive. Defines the data block.
HALTHaltStops after the checksum is ready.