4.3.2 Shifting and Rotating Bits

The 8086-based processors provide a complete set of instructions for shifting and rotating bits. Shift instructions move bits a specified number of places to the right or left. The last bit in the direction of the shift goes into the carry flag, and the first bit is filled with 0 or with the previous value of the first bit.

Rotate instructions also move bits a specified number of places to the right or left. For each bit rotated, the last bit in the direction of the rotate operation moves into the first bit position at the other end of the operand. With some variations, the carry bit is used as an additional bit of the operand. Figure 4.3 illustrates the eight variations of shift and rotate instructions for eight-bit operands. Notice that SHL and SAL are identical.

All shift instructions use the same format. Before the instruction executes, the destination operand contains the value to be shifted; after the instruction executes, it contains the shifted operand. The source operand contains the number of bits to shift or rotate. It can be the immediate value 1 or the CL register. The 8088 and 8086 processors do not accept any other values or registers with these instructions.

Summary: The shift instruction allows you to change masks during program execution.

Masks for logical instructions can be shifted to new bit positions. For example, an operand that masks off a bit or group of bits can be shifted to move the mask to a different position, allowing you to mask off a different bit each time the mask is used. This technique, illustrated in the following example, is useful only if the mask value is unknown until run time.

.DATA

masker BYTE 00000010y ; Mask that may change at run time

.CODE

.

.

.

mov cl, 2 ; Rotate two at a time

mov bl, 57h ; Load value to be changed 01010111y

rol masker, cl ; Rotate two to left 00001000y

or bl, masker ; Turn on masked values ---------

; New value is 05Fh 01011111y

rol masker, cl ; Rotate two more 00100000y

or bl, masker ; Turn on masked values ---------

; New value is 07Fh 01111111y

Starting with the 80186 processor, you can use eight-bit immediate values larger than 1 as the source operand for shift or rotate instructions, as shown below:

shr bx, 4 ; 9 clocks, 3 bytes on 80286

The following statements are equivalent if the program must run on the 8088 or 8086 processor:

mov cl, 4 ; 2 clocks, 3 bytes on 80286

shr bx, cl ; 9 clocks, 2 bytes on 80286

; 11 clocks, 5 bytes