← r0mheat z80 lessons: all projects

Z80 assembly: Logic and bits

Use masks to keep, clear, or toggle bits. Test one bit without changing the value.

AND · OR · XOR · BIT · SET · RES

AND keeps bits set in both values. OR sets a bit if either value has it. XOR sets a bit when the values differ. BIT tests a bit. SET makes it 1. RES makes it 0.

AND, OR and XOR update S, Z, H, P/V, N and C. BIT updates S, Z, H and P/V, while preserving C. SET and RES do not change flags.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program starts with 11001100b. It combines masks, tests bit 7, clears it, then sets bit 0.

Registers, flags and program bytes

Flags

A mask is a value used to select bits. In this example, 0Fh keeps the low nibble. 80h selects bit 7. BIT sets Z when the tested bit is 0, sets H, clears N and preserves C. This page ignores undocumented X and Y bits.

Program memory

Execution trace

#AddressInstructionResultT-states

Bit operation effects

InstructionInput AOther value / bitOutput A
AND 0FhCCh0Fh0Ch
OR 80h0Ch80h8Ch
XOR 0Ch8Ch0Ch80h
RES 7,A80hbit 700h
SET 0,A00hbit 001h

AND with 0Fh is one way to keep only the low four bits. OR with 80h sets the top bit.

The examples use register A. The same bit instructions can also operate on the byte at (HL). Input/output ports and interrupts are not modeled.

Mnemonic glossary

Program mnemonics and directives
NameStands forMeaning here
LDLoadLoads the first byte into A.
ANDLogical ANDKeeps bits set in both inputs.
ORLogical ORSets bits present in either input.
XORExclusive ORSets bits that differ.
BITBit testTests one bit without changing A.
SETSet bitChanges the selected bit to 1.
RESReset bitChanges the selected bit to 0.
HALTHaltStops this lesson’s CPU.