← r0mheat z80 lessons: all projects

Z80 assembly: Rotates and shifts

Move bits left or right. The bit that leaves the byte can enter the carry flag.

RLCA · RLA · RRCA · RRC · SLA · SRA · SRL

A rotate moves bits around a byte or through the carry flag. A shift moves bits and fills the empty place with 0, or keeps the sign bit for SRA. Carry records the bit that moved out.

Accumulator rotates take 4 T-states. CB-prefixed register rotates and shifts take 8. These CB forms set S, Z and P/V from the result; accumulator rotates preserve those three flags.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The accumulator example rotates 81h. Then B uses CB-prefixed rotate and shift instructions. Step one instruction to follow each outgoing bit.

Registers, flags and program bytes

Flags

C is the carry flag. For RLA and RR, its old value moves into the byte. The new C receives the bit that leaves. This page ignores undocumented X and Y bits.

Program memory

Execution trace

#AddressInstructionResultT-states

Watch the bits move

10000001

OperationBeforeAfterCarry out
RLCA81h03h1
RLA03h, C=107h0
SRA B80hC0h0
SRL BC0h60h0

SRA keeps bit 7. This preserves the sign of a signed value. SRL shifts in 0, so it is a logical shift.

This lesson uses documented rotate and shift instructions. The undocumented SLL operation is not included.

Mnemonic glossary

Program mnemonics and directives
NameStands forMeaning here
LDLoadLoads test values into A and B.
RLCARotate Left Circular AccumulatorMoves bit 7 to bit 0 and carry.
RLARotate Left Accumulator through CarryMoves carry into bit 0.
RRCARotate Right Circular AccumulatorMoves bit 0 to bit 7 and carry.
RRCRotate Right CircularRotates B and updates result flags.
SLAShift Left ArithmeticShifts B left and fills bit 0 with 0.
SRAShift Right ArithmeticShifts B right and keeps bit 7.
SRLShift Right LogicalShifts B right and fills bit 7 with 0.
HALTHaltStops this lesson’s CPU.