Shift and Rotate Instructions
Shift and Rotate Instructions
Shift and Rotate Instructions
Sheeza Zaheer
Lecturer
University of Management and Technology
Lahore Campus
2
● References
■ Chapter 7, Section 7.2, 7.3, 7.4, Ytha Yu and Charles
Marut, “Assembly Language Programming and
Organization of IBM PC
Shift/Rotate Instructions
4
4
Shift Instructions
5
5
The SHL Instruction
6
● Shifts the bit in destination to the left
0
CF
● Effects on flags:
■ SF, PF, ZF reflects the result
■ AF is undefined
■ CF = last bit shifted out
■ OF = 1 if result changes sign on last shift
6
Contd..
7
● Example:
■ DH = 8Ah
■ CL = 3
■ Initially, CF = 1
■ Value of DH and CF after executing instruction:
SHL DH, CL
Solution: DH = 50h, CF = 0
Explanation:
1000 1010 CF= 1
0001 0100 CF= 1 1st shift
0010 1000 CF= 0 2nd shift
7 0101 0000 CF= 0 3rd shift
Cont.
8
9
The SHR Instruction
10
● Performs right shift on destination operand.
● A 0 is shifted into MSB and rightmost bit is
shifted to CF.
● The effect on flag is same as SHL.
CF
■ Explanation:
1000 1010 CF= 1
0100 0101 CF= 0
0010 0010 CF= 1
11
The SAR Instruction
12
● Operates like SHR, with one difference: the MSB retains its
original value.
CF
● If number is even, one right shift is same as divide the number
by 2.
● If number is odd, one right shift halves it and rounds down to
nearest integer.
● Example: BL = 0000 0101b = 5d
After one right shift:
BL = 0000 0010b = 2d
● If a signed interpretation is being given, use SAR. (preserves
12
the MSB)
Examples
13
● Use right shift to divide unsigned number 65143 by 4. Put
quotient in AX.
● Solution:
MOV AX, 65143
MOV CL, 2
SHR AX, CL
● If AL contains -15, give the decimal value of AL after SAR
AL, 1 is performed.
● Solution:
The instruction will divide –15 by 2 and round it down to –8
AL = 1111 0001b
13AL = 1111 1000b = – 8
Rotate Instructions
14
● ROL (Rotate Left)
CF
14
Contd..
15
● ROR (Rotate Right)
CF
18
Example
19
● Suppose DH contains 8Ah, CF = 1, and CL contains 3.
What are the values of DH and CF after the instruction
ROL DH, CL is executed?
● Solution:
CF DH
Initial value 1 1000 1010
After 1 right rotation 1 0001 0101
After 2 right rotations 0 0010 1010
After 3 right rotations 0 0101 0100 = 54h
19
Example
20
● Suppose DH contains 8Ah, CF = 1, and CL contains 3.
What are the values of DH and CF after the instruction
RCR DH, CL is executed?
● Solution:
CF DH
Initial value 1 1000 1010
After 1 right rotation 0 1100 0101
After 2 right rotations 1 0110 0010
After 3 right rotations 0 1011 0001 = B1h
20
Example
21
● Use ROL to count the number of 1 bits in BX, without
changing BX. Put answer in AX
● Solution:
XOR AX, AX
MOV CX, 16
TOP:
ROL BX, 1
JNC NEXT
INC AX
NEXT:
LOOP TOP
21