Lec 13 Shift and Rotate
Lec 13 Shift and Rotate
Assembly Language
Hareem-e-Sahar
1
Shift Instructions
• Shifting means to move bits right and left
inside an operand.
• x86 has a rich set of shift instructions, all
affecting carry and overflow flags.
– Logical vs Arithmetic Shifts
2
Shift and Rotate Instructions
3
Logical vs Arithmetic Shifts
• A logical shift fills the newly created bit position
with zero:
4
SHL Instruction
• The SHL (shift left) instruction performs a
logical left shift on the destination operand,
filling the lowest bit with 0.
5
Fast Multiplication using SHL
Shifting left 1 bit multiplies a number by 2
mov dl,5
shl dl,1
6
SHR Instruction
• The SHR (shift right) instruction performs a
logical right shift on the destination operand.
The highest bit position is filled with a zero.
7
SAL and SAR Instructions
• SAL (shift arithmetic left) is identical to SHL.
• SAR (shift arithmetic right) performs a right
arithmetic shift on the destination operand.
8
ROL Instruction
• ROL (rotate) shifts each bit to the left
• The highest bit is copied into both the Carry
flag and into the lowest bit
• No bits are lost
mov al,11110000b
rol al,1 ; AL = 11100001b
mov dl,3Fh
rol dl,4 ; DL = F3h
9
10
ROR Instruction
• ROR (rotate right) shifts each bit to the right
• The lowest bit is copied into both the Carry flag
and into the highest bit
• No bits are lost
mov al,11110000b
ror al,1 ; AL = 01111000b
mov dl,3Fh
ror dl,4 ; DL = F3h
11
12
RCL Instruction
• RCL (rotate carry left) shifts each bit to the left
• Copies the Carry flag to the least significant bit
• Copies the most significant bit to the Carry flag
CF
clc ; CF = 0
mov bl,88h ; CF = 0, BL = 10001000b
rcl bl,1 ; CF = 1, BL = 00010000b
rcl bl,1 ; CF = 0, BL = 00100001b
13
RCR Instruction
• RCR (rotate carry right) shifts each bit to the right
• Copies the Carry flag to the most significant bit
• Copies the least significant bit to the Carry flag
stc ; CF = 1
mov ah,10h ; CF = 1, AH = 00010000b
rcr ah,1 ; CF = 0, AH = 10001000b
14
• Lecture made from “Assembly language for
x86 processors” by Kip Irvine
19