Z80 assembly: Rotates and shifts
Move bits left or right. The bit that leaves the byte can enter the carry flag.
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.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
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
| # | Address | Instruction | Result | T-states |
|---|
Watch the bits move
10000001
| Operation | Before | After | Carry out |
|---|---|---|---|
| RLCA | 81h | 03h | 1 |
| RLA | 03h, C=1 | 07h | 0 |
| SRA B | 80h | C0h | 0 |
| SRL B | C0h | 60h | 0 |
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
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads test values into A and B. |
| RLCA | Rotate Left Circular Accumulator | Moves bit 7 to bit 0 and carry. |
| RLA | Rotate Left Accumulator through Carry | Moves carry into bit 0. |
| RRCA | Rotate Right Circular Accumulator | Moves bit 0 to bit 7 and carry. |
| RRC | Rotate Right Circular | Rotates B and updates result flags. |
| SLA | Shift Left Arithmetic | Shifts B left and fills bit 0 with 0. |
| SRA | Shift Right Arithmetic | Shifts B right and keeps bit 7. |
| SRL | Shift Right Logical | Shifts B right and fills bit 7 with 0. |
| HALT | Halt | Stops this lesson’s CPU. |