6. Shifting And Rotating

There are 4 shift and 4 rotate instructions, 2 going left and 2 going right.

ASL and ASR are arithmetic shifts while LSL and LSR are logical shifts. What is the difference ? Taking the logical shifts first we have :

LSL.size Dx,Dy

or

LSL.size #data,Dy

or

LSL.W address

LSR has the same format, it just shifts in the opposite direction.

For the first two variations above, the data in Dy is affected and the size can be byte, word or long. The number of shifts that take place is defined by the value in register Dx or in the immediate data.

For the final variation, the size must be word only, and the data in thay address and the address above it, is affected. For this format, there can only be a single shift at a time.

What happens is that the data is shifted by a single bit at a time. The bit that is shifted 'out' of the register is placed into the C and X flags, while the 'vacant' bit is filled with a zero.

Consider this example :

Example 4.2. LSL Example

MOVEQ    #$81,D0     ; D0.B is 1000 0001
LSL.B    #1,D0       ; Now it is 0000 0010 and C and X are 1
MOVEQ    #5,D2
LSL.B    D2,D0       ; Now D0.B is 0100 0000

Shifting the opposite way gives this :

Example 4.3. LSR Example

MOVEQ    #$81,D0     ; D0.B is 1000 0001
LSR.B    #1,D0       ; Now it is 0100 0010 and C and X are 1
MOVEQ    #5,D2
LSR.B    D2,D0       ; Now D0.B is 0000 0010

LSL is a quick way of multiplying an unsigned number by 2 for each bit shifted.

LSR is a quick way of dividing an unsigned number by 2 - but the fractions are lost. Another couple of examples :

Example 4.4. LSL Multiplication Example

MOVEQ    #8,D0       ; D0.L holds 8
LSL.L    #1,D0       ; D0.L now holds 16
LSL.L    #2,D0       ; D0.L now holds 64

Example 4.5. LSR Division Example

MOVEQ    #10,D0      ; D0.L holds 10
LSR.L    #1,D0       ; D0.L now holds 5
LSR.L    #1,D0       ; D0.L now holds 2 - note the remainder is 'lost'

When specifying the number of shifts as immeditae data, only values from 1 to 8 can be used. If the number of shifts required is greater than this, then a register counter has to be used. When shifting memory, the shift is always a single bit.

After a shift in either direction the flags are set as follows :

The arithmetic shifts - ASL and ASR - preserve the sign of the value by duplicating the previous value of the sign bit in the new sign bit, so everything shifts as above, but the most significant bit of the byte, word or long being shifted, is shifted back into itself.