CIE AS & A Level Computer Science, section 4.3 (Bit manipulation)
What a shift does
A binary shift moves every bit of a binary number a number of places to the left or right.
Logical shifts
- Logical left shift (LSL): bits move left, and zeros enter on the right. The leftmost bit is lost. Shifting left by 1 multiplies by 2 (if no bit is lost).
- Logical right shift (LSR): bits move right, and zeros enter on the left. Shifting right by 1 divides by 2, discarding the remainder.
Arithmetic shift
An arithmetic shift keeps the sign of a two's complement number. In a right shift the sign bit is copied into the vacated place.
Cyclic shift (rotate)
Bits that fall off one end are put back at the other end, so none are lost.
Assembly instructions
LSL #n shifts the ACC left by places, and LSR #n shifts it right by places, with zeros introduced.
Uses
Quick multiplication and division by powers of 2, and moving bits into position to test or set them.
Common mistake: using a logical right shift on a negative two's complement number and expecting the sign to stay. A logical shift puts a 0 on the left, which changes the sign. Use an arithmetic shift to preserve the sign.
Exam tip: show the 8-bit number before and after the shift, with the bits that are lost and the bits introduced. Say whether the shift is logical, arithmetic or cyclic.
Check yourself
What is the effect of a logical left shift by 1 on 00000110?
00001100, which doubles the value (6 becomes 12).
What is the difference between a logical and a cyclic shift?
A logical shift loses the bits that fall off the end and brings in zeros, while a cyclic shift moves them round to the other end.
Which instruction shifts the accumulator right?
LSR #n.