Shift and Rotate Instructions: Sahar Mosleh California State University San Marcos 1
Shift and Rotate Instructions: Sahar Mosleh California State University San Marcos 1
Shift and Rotate Instructions: Sahar Mosleh California State University San Marcos 1
Rotate Instructions
• All the following instructions affect the overflow and the carry
flag.
SHL Shift left
SHR Shift right
SAL Shift arithmetic left
SAR Shift arithmetic right
ROL Rotate left
ROR Rotate right
RCL Rotate carry left
RCR Rotate carry right
SHLD double precision shift left
SHRD double precision shift right
Sahar Mosleh California State University San Marcos Page 2
Logical Shift vs Arithmetic Shift
• There are two basic ways to shift the bits in a number.
• The first called a logical shift, fills the newly created bit position
with Zero.
• In the following diagram, a byte is logically shifted one position
to the right.
• Note that bit 7 is assigned 0
0
CF
• The newly created bit position is filled with a copy of the original
numbers sign bit.
CF
• For example, the binary value 11001111, has a 1 in the sign bit.
CF
• The first operand is the destination and the second is shift count.
SHL destination, count
0
CF
CF
• The syntax and operands for SHR and SAR are identical to those
for SHL and SHR.
CF
• Bit rotation differs from bit shifting in that the former does not
lose any bits.
• You can use ROL to exchange the upper (4-7 bit) and lower
(bits 0-3) halves of the byte.
CF
• In the following example, the lowest bit is copied into the carry
flag and into the highest bit of the result
• The RCL (Rotate Carry left) instruction shifts each bit to the left
copies the carry flag to least significant bit (LSB), and copies the
most significant bit (MSB) into the carry flag.
CF
• If you think of the carry flag as just an extra bit added to the high
end of the number, then RCL becomes a simple rotate left
operation.
• The first RCL instruction moves the high bit of bl into the carry
flag and shifts all other bits to the left
• The second RCL instruction moves the carry flag into the lowest
bit position
CLC ; CF = 0
mov bl, 88h ; CF, BL = 0 10001000b
rcl bl, 1 ; CF, BL = 1 00010000b
rcl b1, 1 ; CF, BL = 0 00100001b
.data
testval byte 01101010b
.code
shr testval, 1 ; shift LSB into the carry flag
jc quit ; exit if carry flag set
rcl testval, 1 ; else restore the number
• The RCR (Rotate Carry Right) instruction shifts each bit to the
right, copies the right flag into the most significant bit, and
copies the least significant bit into the carry flag.
CF
STC ; CF = 1
mov ah, 10h ; CF, Ah = 00010000 1
rcr ah, 1 ; CF, Ah = 10001000 0