Understanding Shifts and Rotations
Shift and rotate instructions move the bits within a register. This is often done to perform arithmetic: shifting a number left by one position is equivalent to multiplying by 2, and shifting right is equivalent to integer dividing by 2.
Key Difference:
- Shift: The bit that leaves one end is discarded, and a new bit (0 or the sign bit) enters the other end.
- Rotate: The bit that leaves one end wraps around to enter the other end, forming a circle.
Arithmetic Shifts (SLA and SRA)
Arithmetic shifts are best for multiplication and division because they handle the sign of the number correctly.
Instruction | Action | Purpose |
---|---|---|
SLA R |
Shift Left Arithmetic: Bit 7 moves to Carry flag; bit 0 becomes 0. | Multiply R by 2. |
SRA R |
Shift Right Arithmetic: Bit 0 moves to Carry flag; bit 7 (the sign bit) is duplicated. | Divide R by 2 (signed). |
Example: Fast Multiplication
LD A, 5 ; A = 00000101b (5 decimal)
SLA A ; A = 00001010b (10 decimal) - Multiplied by 2
Rotations (RLC, RRC, RL, RR)
Rotations are primarily used for general bit manipulation and sometimes for multi-byte arithmetic, as the Carry flag (C) can be included in the rotation path.
Instruction | Action | Carry Flag Involvement |
---|---|---|
RLC R |
Rotate Left Circular: Bit 7 moves to the Carry flag AND back into bit 0. | Not integrated (independent of C). |
RR R |
Rotate Right through Carry: Bit 0 moves to Carry; Carry moves into bit 7. | Integrated (uses C for the rotation). |
Rotation through Carry Example
The RR
and RL
instructions are perfect for rotating a 16-bit value (like two 8-bit registers, H and L) by one position.
; Assume HL holds a 16-bit number
RL L ; Rotate the low byte (L) through the Carry flag
RL H ; Rotate the high byte (H) through the same Carry flag
; The bit that exited L entered H, achieving a 16-bit rotation.
``×××