0% found this document useful (0 votes)
7 views31 pages

CH 7

The document provides an overview of shift and rotate instructions in assembly language, detailing logical and arithmetic shifts, including SHL, SHR, SAL, and SAR. It explains how these instructions manipulate bits, affect flags, and their use cases, such as multiplication and division by powers of 2. Additionally, it covers rotation instructions (ROL, ROR) and their applications in handling large numbers and binary multiplication.

Uploaded by

M Ahmed Butt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views31 pages

CH 7

The document provides an overview of shift and rotate instructions in assembly language, detailing logical and arithmetic shifts, including SHL, SHR, SAL, and SAR. It explains how these instructions manipulate bits, affect flags, and their use cases, such as multiplication and division by powers of 2. Additionally, it covers rotation instructions (ROL, ROR) and their applications in handling large numbers and binary multiplication.

Uploaded by

M Ahmed Butt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

7.

1 Shift and Rotate Instructions (Simplified Notes)

Shift and rotate instructions are key in assembly language for moving bits left or right within a
number. They affect the Carry Flag (CF) and Overflow Flag (OF).

7.1.1 Logical Shifts vs. Arithmetic Shifts

1. Logical Shift

 Fills empty bit positions with 0.

 Two types:

o SHL (Shift Left): Moves bits left, fills rightmost bit with 0.

o SHR (Shift Right): Moves bits right, fills leftmost bit with 0.

Example (SHR):

 Original: 11001111

 After 1 right shift: 01100111 (CF = 1, because the last shifted bit was 1).

2. Arithmetic Shift

 Preserves the sign bit (leftmost bit).

 Used for signed numbers.

 SAR (Shift Arithmetic Right): Copies the sign bit into the new leftmost bit.

Example (SAR):

 Original: 11001111 (Negative number)

 After 1 right shift: 11100111 (Still negative, CF = 1).

7.1.2 SHL (Shift Left) Instruction

 Performs a logical left shift.

 Syntax: SHL destination, count

o destination = Register or memory

o count = Number of shifts (immediate value or CL register).

Effects:

 Leftmost bit moves into Carry Flag (CF).

 Rightmost bit fills with 0.

Example:

assembly
Copy

Download

mov bl, 8Fh ; BL = 10001111

shl bl, 1 ; BL = 00011110, CF = 1

Uses:

 Multiplication by powers of 2 (e.g., SHL DL,1 = multiply by 2).

7.1.3 SHR (Shift Right) Instruction

 Performs a logical right shift.

 Syntax: SHR destination, count

Effects:

 Rightmost bit moves into Carry Flag (CF).

 Leftmost bit fills with 0.

Example:

assembly

Copy

Download

mov al, 0D0h ; AL = 11010000

shr al, 1 ; AL = 01101000, CF = 0

Uses:

 Unsigned division by powers of 2 (e.g., SHR DL,1 = divide by 2).

7.1.4 SAL & SAR Instructions

1. SAL (Shift Arithmetic Left)

 Same as SHL (fills right with 0).

2. SAR (Shift Arithmetic Right)

 Preserves the sign bit.

 Syntax: SAR destination, count

Example:

assembly

Copy
Download

mov al, 0F0h ; AL = 11110000 (-16)

sar al, 1 ; AL = 11111000 (-8), CF = 0

Uses:

 Signed division by powers of 2 (e.g., SAR DL,3 = divide by 8).

Key Takeaways

Instructio
Type Effect Use Case
n

Multiply unsigned
SHL Logical Shift Left Left shift, CF = last shifted bit
numbers

Right shift, CF = last shifted


SHR Logical Shift Right Divide unsigned numbers
bit

Arithmetic Shift
SAR Right shift, keeps sign bit Divide signed numbers
Right

SAL Arithmetic Shift Left Same as SHL Rarely used (same as SHL)

Remember:

 Logical shifts (SHL/SHR) fill with 0.

 Arithmetic shifts (SAR) preserve the sign bit.

 CF stores the last shifted-out bit.

Extra Notes

 ROL/ROR (Rotate Left/Right): Bits wrap around (no loss).

 RCL/RCR (Rotate with Carry): Includes CF in rotation.

 SHLD/SHRD (Double-Precision Shift): Shifts two operands together.

7.1.5 ROL (Rotate Left) Instruction

 Rotates bits left in a circle (no bits are lost).

 Highest bit moves into Carry Flag (CF) AND the lowest bit.

 Syntax: ROL destination, count


Example:

assembly

Copy

Download

mov al, 40h ; AL = 01000000b

rol al, 1 ; AL = 10000000b, CF = 0

rol al, 1 ; AL = 00000001b, CF = 1

Uses:

 Swapping upper/lower nibbles (e.g., ROL AL, 4 turns 26h into 62h).

 Multibyte rotation: Shifts hex digits (e.g., 6A4Bh → A4B6h after ROL AX,4).

7.1.6 ROR (Rotate Right) Instruction

 Rotates bits right in a circle.

 Lowest bit moves into CF AND the highest bit.

 Syntax: ROR destination, count

Example:

assembly

Copy

Download

mov al, 01h ; AL = 00000001 b

ror al, 1 ; AL = 10000000b, CF = 1

ror al, 1 ; AL = 01000000b, CF = 0

7.1.7 RCL & RCR (Rotate Through Carry)

1. RCL (Rotate Carry Left)

 Shifts left + includes CF in rotation.

 CF becomes the new LSB.

 Syntax: RCL destination, count

Example:

assembly

Copy
Download

clc ; CF = 0

mov bl, 88h ; BL = 10001000b

rcl bl, 1 ; BL = 00010000b, CF = 1

rcl bl, 1 ; BL = 00100001b, CF = 0

2. RCR (Rotate Carry Right)

 Shifts right + includes CF in rotation.

 CF becomes the new MSB.

 Syntax: RCR destination, count

Example:

assembly

Copy

Download

stc ; CF = 1

mov ah, 10h ; AH = 00010000b

rcr ah, 1 ; AH = 10001000b, CF = 0

Key Use:

 Recovering a shifted bit (e.g., use RCL to undo a SHR if CF was set).

7.1.8 Signed Overflow (OF Flag)

 OF is set if rotating/shifting changes the sign bit unexpectedly.

 Examples:

o ROL AL,1 on +127 (01111111b) → -2 (11111110b) → OF = 1.

o SHR AL,1 on -128 (10000000b) → +64 (01000000b) → OF = 1.

 Undefined for shift counts > 1.

7.1.9 SHLD & SHRD (Double-Precision Shifts)

1. SHLD (Shift Left Double)

 Shifts dest left, fills empty bits from source’s MSBs.

 Source remains unchanged.

 Syntax: SHLD dest, source, count


Example:

assembly

Copy

Download

.data

wval WORD 9BA6h

.code

mov ax, 0AC36h

shld wval, ax, 4 ; wval = BA6Ah (fills from AX’s bits)

2. SHRD (Shift Right Double)

 Shifts dest right, fills empty bits from source’s LSBs.

 Syntax: SHRD dest, source, count

Example:

assembly

Copy

Download

mov ax, 234Bh

mov dx, 7654h

shrd ax, dx, 4 ; AX = 4234h (fills from DX’s bits)

Uses:

 Bitmap manipulation (e.g., screen graphics).

 Long integer math (multiplication/division).

Key Summary Table

Instruction Type Effect Use Case

ROL Rotate Left Bits wrap left, CF = MSB Swap nibbles

ROR Rotate Right Bits wrap right, CF = LSB Circular shifts

RCL Rotate Left Through Carry Includes CF in rotation Recover lost bits
Instruction Type Effect Use Case

RCR Rotate Right Through Carry Includes CF in rotation Precision shifts

SHLD Double Shift Left Fills from source’s MSBs Bitmap operations

SHRD Double Shift Right Fills from source’s LSBs Long integer math

Final Notes

 Rotations (ROL/ROR) preserve all bits (no data loss).

 Carry-based rotations (RCL/RCR) are useful for multi-precision arithmetic.

 Double shifts (SHLD/SHRD) efficiently handle large data blocks.

Section Review (Easy Explanations & Answers)

1. Which instruction shifts left and copies the highest bit into CF and the lowest bit?

Answer: ROL (Rotate Left)

 How it works: Bits move left, the highest bit goes to CF and the lowest bit.

 Example:

assembly

Copy

Download

mov al, 80h ; AL = 10000000b

rol al, 1 ; AL = 00000001b, CF = 1

2. Which instruction shifts right, copies the lowest bit into CF, and puts CF into the highest bit?

Answer: RCR (Rotate Carry Right)

 How it works: Bits move right, the lowest bit goes to CF, and CF fills the highest bit.

 Example:

assembly

Copy

Download
stc ; Set CF = 1

mov al, 01h ; AL = 00000001b

rcr al, 1 ; AL = 10000000b, CF = 1

3. Which instruction does this?

Before: CF,AL = 1 11010101


After: CF,AL = 1 10101011
Answer: RCL (Rotate Carry Left)

 Why?

o The bits shifted left.

o The CF (1) was inserted at the end (LSB).

o The MSB (1) moved into CF again.

4. What happens to CF when SHR AX,1 executes?

Answer:

 The lowest bit (LSB) of AX is copied into CF.

 Example:

assembly

Copy

Download

mov ax, 0005h ; AX = 00000000 00000101b

shr ax, 1 ; AX = 00000000 00000010b, CF = 1

5. Challenge: Shift AX’s lowest bit into BX’s highest bit without SHRD

Solution:

1. Shift AX right to move its LSB into CF.

2. Shift BX left and let CF fill its LSB.

3. Rotate BX left to move that bit to the MSB.

Code:

assembly

Copy

Download
mov cx, 16 ; Number of bits to shift (for 16-bit registers)

; Without SHRD:

shr ax, 1 ; Move AX's LSB into CF

rcl bx, 1 ; Shift BX left, insert CF into LSB

rol bx, 1 ; Move the new bit to MSB

; With SHRD:

shrd bx, ax, 1 ; Directly shift AX's LSB into BX's MSB

6. Challenge: Calculate parity of a 32-bit number in EAX

Goal: Count the number of 1 bits in EAX and set PF (Parity Flag) if the count is even.

Steps:

1. Use a loop to shift each bit into CF.

2. Count how many times CF = 1.

3. Check if the count is even/odd.

Code:

assembly

Copy

Download

mov ecx, 32 ; 32 bits in EAX

xor bl, bl ; BL will count '1's

CountBits:

shr eax, 1 ; Shift LSB into CF

adc bl, 0 ; Add CF to BL (BL = BL + CF)

loop CountBits

test bl, 1 ; Check if BL is odd (PF = 1 if even)

jp ParityEven ; Jump if parity even

; Else, PF = 0 (odd)
Summary Table

Questio
Answer Key Idea
n

1 ROL Rotates left, CF = MSB → LSB

2 RCR Rotates right, CF → MSB, LSB → CF

3 RCL Rotates left + includes CF in rotation

4 CF = LSB of AX SHR copies LSB into CF

Use SHR + RCL or SHR


5 Move bits between registers
D

6 Count 1s → set PF Loop + SHR + ADC

7.2 Shift and Rotate Applications (Easy Notes)

7.2.1 Shifting Multiple Doublewords (Large Numbers)

Problem: How to shift a big number (stored in multiple bytes/words) left or right.
Solution: Use SHR/SHL + RCR/RCL to chain shifts across bytes.

Steps (for 3-byte right shift):

1. Shift the highest byte ([ESI+2]) right → Its LSB goes to Carry Flag (CF).

assembly

Copy

Download

shr array[esi+2], 1 ; Example: 10011001 → 01001100 (CF=1)

2. Rotate middle byte ([ESI+1]) right → Fill MSB with CF, new LSB to CF.

assembly

Copy

Download

rcr array[esi+1], 1 ; 10011001 → 11001001 (CF=1)

3. Rotate lowest byte ([ESI]) right → Repeat the process.


assembly

Copy

Download

rcr array[esi], 1 ; 10011001 → 11001100 (CF=1)

Final Result:

Copy

Download

[ESI+2]: 01001100

[ESI+1]: 11001100

[ESI]: 11001100

Key Idea:

 Use SHR for the first shift (to set CF).

 Use RCR for remaining shifts (to carry bits between bytes).

7.2.2 Binary Multiplication (Faster than MUL)

Trick: Multiply using SHL (left shifts) for powers of 2.

Example: Multiply EAX = 123 by 36:

1. Break 36 into powers of 2:

o 36 = 32 (2⁵) + 4 (2²)

2. Multiply 123 by each part:

assembly

Copy

Download

mov eax, 123 ; EAX = 123

mov ebx, eax ; EBX = 123

shl eax, 5 ; EAX = 123 * 32 = 3936

shl ebx, 2 ; EBX = 123 * 4 = 492

add eax, ebx ; EAX = 3936 + 492 = 4428

Why It Works:

 SHL EAX, n = EAX × 2ⁿ (e.g., SHL EAX,3 = ×8).

 Add partial results for non-power-of-2 multipliers.


Visualization:

Copy

Download

123 (01111011) × 36 (00100100)

= (123 SHL 5) + (123 SHL 2)

= 3936 + 492

= 4428

Key Takeaways

Concept How It Works Example

Chain SHR + RCR to shift large SHR byte3,1 → RCR byte2,1 → RCR
Multi-byte Shift
numbers. byte1,1

Fast Use SHL for powers of 2, add


123 × 36 = (123×32) + (123×4)
Multiplication results.

Need Practice? Try these:

1. Write code to left-shift a 4-byte array.

2. Multiply AX by 10 using shifts (10 = 8 + 2).

7.2.3 Displaying Binary Bits (Easy Explanation)

Goal: Convert a 32-bit binary number (like EAX = 1101...) into a readable ASCII string (like "1101...").

How It Works:

1. Loop 32 times (1 for each bit in EAX).

2. Shift left (SHL) to move the highest bit into the Carry Flag (CF).

3. Check CF:

o If CF=0, store '0' in the buffer.

o If CF=1, store '1'.

4. Repeat until all 32 bits are processed.

Code Example:

BinToAsc PROC

push ecx ; Save registers

push esi
mov ecx, 32 ; 32 bits to process

L1: shl eax, 1 ; Shift left, top bit → CF

mov BYTE PTR [esi], '0' ; Default '0'

jnc L2 ; If CF=0, skip next line

mov BYTE PTR [esi], '1' ; Else, store '1'

L2: inc esi ; Move to next buffer position

loop L1 ; Repeat for all bits

pop esi ; Restore registers

pop ecx

ret

BinToAsc ENDP

Example Output:
If EAX = 3 (000...0011), the buffer becomes:
"00000000000000000000000000000011"

7.2.4 Extracting File Date Fields (Easy Explanation)

Goal: Extract day, month, and year from a packed 16-bit date stamp (like DX in MS-DOS).

Date Stamp Format:

Bits Field Range Example (March 10, 1999)

0-4 Day 1-31 10 → 01010

5-8 Month 1-12 3 → 0011

9-15 Year 0-127 (1980+) 1999-1980 = 19 → 10011

Step-by-Step Extraction:

1. Extract Day (Bits 0-4)

 Mask DL to keep only the first 5 bits:

assembly
Copy

Download

mov al, dl ; Copy DL (bits 0-7)

and al, 00011111b ; Clear bits 5-7 → keeps bits 0-4

mov day, al ; Save day (1-31)

2. Extract Month (Bits 5-8)

 Shift right 5 times, then mask:

assembly

Copy

Download

mov ax, dx ; Copy DX (full date)

shr ax, 5 ; Shift right 5 → bits 5-8 now at bits 0-3

and al, 00001111b ; Clear bits 4-7 → keeps bits 0-3

mov month, al ; Save month (1-12)

3. Extract Year (Bits 9-15)

 Use DH (bits 8-15), shift right 1 bit (since year starts at bit 9), then add 1980:

assembly

Copy

Download

mov al, dh ; Copy DH (bits 8-15)

shr al, 1 ; Shift right 1 → bits 9-15 now at bits 8-14

mov ah, 0 ; Clear AH to convert to 16-bit

add ax, 1980 ; Year = AX + 1980

mov year, ax ; Save year (e.g., 1999)

Key Takeaways

Task Method Example Code

Show binary SHL + check CF shl eax,1 → mov [esi], '0'/'1'

Get day Mask DL with 00011111b and al, 00011111b


Task Method Example Code

Get month Shift right 5 + mask 00001111b shr ax,5 → and al, 00001111b

Get year Shift DH right 1 + add 1980 shr al,1 → add ax, 1980

Why This Matters:

 Binary display helps debug hardware/low-level code.

 Date extraction is used in file systems (e.g., FAT32).

Review 2
1. Write assembly language instructions that calculate EAX * 24 using binary multiplication.

To multiply EAX by 24, we can use a combination of shifting and adding. Multiplying by 24 is the
same as multiplying by 16 (2^4) and then adding the result of multiplying by 8 (2^3).

asm

CopyEdit

shl eax, 4 ; Multiply EAX by 16 (shift left by 4)

add eax, eax ; Add EAX to itself (multiply EAX by 2)

Explanation:

 The shl eax, 4 instruction shifts the bits of EAX left by 4 positions, effectively multiplying it by
16.

 The add eax, eax instruction doubles EAX, which is the same as multiplying by 2.

 This results in EAX being multiplied by 24 (16 + 8).

2. Write assembly language instructions that calculate EAX * 21 using binary multiplication.

To multiply EAX by 21, we can use the same approach as before, utilizing shifts and adds. Multiplying
by 21 can be broken down as multiplying by 16 (2^4) and adding the result of multiplying by 4 (2^2)
and 1 (2^0).

asm

CopyEdit

shl eax, 4 ; Multiply EAX by 16 (shift left by 4)

mov ebx, eax ; Copy the result to EBX

shl ebx, 2 ; Multiply EBX by 4 (shift left by 2)


add eax, ebx ; Add EBX (which is EAX*4) to EAX (which is EAX*16)

Explanation:

 The shl eax, 4 shifts EAX left by 4 positions, multiplying by 16.

 The mov ebx, eax saves the current value of EAX (which is already multiplied by 16).

 The shl ebx, 2 multiplies the value in EBX by 4.

 Finally, the add eax, ebx adds the value of EBX (EAX * 4) to EAX (EAX * 16), resulting in EAX *
21.

3. What change would you make to the BinToAsc procedure in Section 7.2.3 in order to display the
binary bits in reverse order?

To reverse the order of the binary bits displayed by the BinToAsc procedure, you would need to
modify the loop where the binary bits are extracted and printed. Instead of printing the bits in the
order they are extracted (starting from the most significant bit), you would start from the least
significant bit.

Here is an approach to modify the procedure to display the bits in reverse order:

asm

CopyEdit

; Assuming the binary value is in the EAX register

mov ecx, 32 ; Set loop counter to 32 bits

mov ebx, eax ; Copy the value to EBX

xor edx, edx ; Clear the EDX register for the remainder

reverse_loop:

shl ebx, 1 ; Shift left to bring the next bit into the carry flag

jc print_bit ; If the carry flag is set, it's a 1

; If the carry flag is not set, print 0

mov dl, '0' ; Move ASCII '0' into DL

call PrintChar

jmp next_bit

print_bit:

mov dl, '1' ; Move ASCII '1' into DL

call PrintChar
next_bit:

loop reverse_loop ; Repeat for all 32 bits

Explanation:

 The loop goes through all 32 bits of the number.

 The shl ebx, 1 instruction shifts the bits to the left, effectively moving the next bit into the
carry flag.

 The jc print_bit checks if the carry flag is set, which indicates that the current bit is 1. If not, it
prints 0.

 This process prints the least significant bit first and works its way to the most significant bit,
reversing the order.

4. The time stamp field of a file directory entry uses bits 0 through 4 for the seconds, bits 5 through
10 for the minutes, and bits 11 through 15 for the hours. Write instructions that extract the
minutes and copy the value to a byte variable named bMinutes.

Assuming the timestamp is stored in a 2-byte variable timestamp (or WORD), here are the
instructions to extract the minutes (bits 5 through 10) and store them in bMinutes:

asm

CopyEdit

mov ax, [timestamp] ; Load the timestamp into AX

shr ax, 5 ; Shift right by 5 to discard the seconds

and ax, 3Fh ; Mask out everything except the lower 6 bits (the minutes)

mov [bMinutes], al ; Move the result (lower byte) into bMinutes

Explanation:

 The mov ax, [timestamp] instruction loads the timestamp into the AX register.

 The shr ax, 5 instruction shifts the timestamp right by 5 bits, discarding the seconds portion
(bits 0 through 4).

 The and ax, 3Fh instruction masks out the upper bits and keeps only the lower 6 bits, which
correspond to the minutes.

 Finally, the mov [bMinutes], al instruction stores the result (lower byte of AX) into the
bMinutes variable.

7.3 Multiplication and Division Instructions – Easy Notes

In Assembly language, you can do multiplication and division using special instructions. These work
with 8-bit, 16-bit, 32-bit, and (in 64-bit mode) even 64-bit numbers.

 MUL → Used for unsigned multiplication (positive numbers).

 IMUL → Used for signed multiplication (positive and negative).


 DIV → Used for unsigned division.

 IDIV → Used for signed division.

7.3.1 MUL Instruction (Unsigned Multiplication)

The MUL instruction is used to multiply unsigned numbers (only positive values). It works differently
depending on the size of the numbers you use:

📌 3 Versions of MUL (in 32-bit mode):

Operand Size Multiplier Multiplicand Result (Product)

8-bit reg/mem8 AL in AX (16-bit result)

16-bit reg/mem16 AX in DX:AX (32-bit result)

32-bit reg/mem32 EAX in EDX:EAX (64-bit result)

You do not give two operands. You only give one, and the CPU already knows what to multiply it
with (like AL, AX, or EAX).

✅ Key Points:

 You can multiply a register or memory value, but not an immediate value (like a direct
number).

 The result (product) is always twice the size of the numbers being multiplied.

 MUL sets flags:

o Carry Flag (CF) and Overflow Flag (OF) are set if the upper half of the result is not
zero.

o If the upper part is zero, both flags are cleared.

💡 Example (16-bit): If you multiply AX (16-bit) by another 16-bit value, the result is stored in DX:AX:

 AX × value = DX:AX

 DX holds the upper 16 bits, and AX holds the lower 16 bits.

7.3.2 IMUL Instruction – (Signed Multiply)

The IMUL instruction is used when multiplying signed numbers (positive or negative). Unlike MUL, it
keeps track of the sign in the result.

✅ How IMUL Handles the Sign:

 IMUL extends the sign bit (the leftmost bit) to make sure the result keeps the correct sign.

 The result (product) is twice the size of the number being multiplied.
📌 3 Formats of IMUL Instruction:

🔹 1. Single-Operand Format:

You give only one operand. The other value is already assumed (like in MUL).

Operand Size Multiplier (you give) Multiplicand (already known) Product (Result)

8-bit reg/mem8 AL in AX (16-bit)

16-bit reg/mem16 AX in DX:AX (32-bit)

32-bit reg/mem32 EAX in EDX:EAX (64-bit)

✅ Overflow is not a problem here because the result space is big enough.

🔸 Flags:

 Carry Flag (CF) and Overflow Flag (OF) are set if the upper half is not just a sign-extension of
the lower half. This helps you check if the upper half can be ignored.

🔹 2. Two-Operand Format (32-bit mode):

Here, you give two values — the destination and the multiplier:

assembly

Copy code

IMUL reg16, reg/mem16

IMUL reg16, imm8

 The first operand is the destination (must be a register).

 The second operand is the number you multiply it with (can be a register, memory, or
immediate value).

 The result is stored in the first operand.

7.3.3 Measuring Program Execution Times – Easy Notes

Programmers often want to compare the speed of different parts of their code. To do that, they
measure how long a procedure or block of code takes to run.

✅ How to Measure Execution Time (Using Irvine32 Library)

The Irvine32 library (used in Assembly programming for Windows) has a handy tool called
GetMseconds, which:

Returns the number of milliseconds that have passed since midnight.


🔧 Basic Steps to Measure Time:

1. Call GetMseconds before running the code you want to test.

2. Run your code (e.g. FirstProcedureToTest)

3. Call GetMseconds again after the code finishes.

4. Subtract the first time from the second to get the elapsed time.

🧠 Example Code:

assembly

Copy code

.data

startTime DWORD ?

procTime1 DWORD ?

procTime2 DWORD ?

.code

; Measure First Procedure

call GetMseconds

mov startTime, eax ; Save start time

call FirstProcedureToTest

call GetMseconds

sub eax, startTime ; Calculate time taken

mov procTime1, eax ; Store result

You repeat the same process for another procedure:

assembly

Copy code

; Measure Second Procedure

call GetMseconds

mov startTime, eax ; Save new start time


call SecondProcedureToTest

call GetMseconds

sub eax, startTime ; Calculate time taken

mov procTime2, eax ; Store result

⚠️Note:

Yes, calling GetMseconds takes a tiny bit of time, but it's so small that it doesn't affect your
comparison much. When comparing two procedures, this overhead is usually the same for both —
so it's okay.

📘 7.3.5 Signed Integer Division – Easy Notes

When dividing signed integers (numbers that can be negative), the process is similar to unsigned
division — but with one big difference:

⚠️Key Rule: You Must Use Sign Extension!

Before doing signed division, the dividend (number you're dividing) must be sign-extended.

🧠 What is Sign Extension?

 Sign extension means:


➤ Copying the sign bit (the leftmost bit) of a smaller value into all the upper bits of a larger
variable.

 It's needed to make sure the computer knows the number is negative when converting it to
a bigger register (like from AX to EAX).

❌ What Happens if You Don't Sign-Extend?

Let’s say we store -101 in AX, and do a signed division:

assembly

Copy code

mov eax, 0 ; Clear EAX

mov ax, wordVal ; wordVal = -101

idiv bx ; divide by 2

📌 But EAX now sees +155 instead of -101 — wrong answer!


✅ Correct Way (Use CWD Instruction):

assembly

Copy code

mov eax, 0 ; Clear EAX

mov ax, wordVal ; Load -101

cwd ; Sign-extend AX into EAX

idiv bx ; Now EAX is properly negative, result is correct

What CWD Does:

 CWD (Convert Word to Doubleword)


➤ Copies the sign bit of AX into the upper 16 bits (into DX).
➤ So now EAX = DX:AX holds a proper signed number.

🔁 Summary:

Step Instruction Purpose

1️⃣ mov ax, wordVal Load signed number

2️⃣ cwd Sign-extend AX into EAX

Perform signed division correctly


3️⃣ idiv bx

🧠 7.3.6 Implementing Arithmetic Expressions – Simple Notes

Now that we’ve learned how to use multiplication (MUL, IMUL) and division (DIV, IDIV), we can start
writing full arithmetic expressions in Assembly, just like we do in high-level languages like C++.

Why Learn This?

 ✅ You’ll understand how compilers optimize arithmetic.

 ✅ You’ll be able to add extra error checking that many compilers skip (e.g., check for
overflow).

 ✅ You’ll know how to use flags (Carry and Overflow) to detect problems like when a
multiplication result doesn’t fit in 32 bits.
📌 Important Tip:

High-level compilers (like C++) often ignore the upper 32 bits when multiplying 32-bit values.

🔍 In Assembly, you have more control — you can:

 Check flags (Carry and Overflow) after multiplication.

 Decide whether the result fits or if there's a problem.

🔧 How to View Assembly Code from C++ (Bonus Tip):

1. While debugging in Visual Studio:

o Right-click → Go to Disassembly

2. To generate a listing file:

o Go to: Project > Properties > Configuration Properties > Microsoft Macro Assembler

o Set:

 Generate Preprocessed Source Listing = Yes

 List All Available Information = Yes

📘 Example 1 – Convert C++ to Assembly

cpp

Copy code

var4 = (var1 + var2) * var3;

Assembly Steps (Unsigned 32-bit integers):

assembly

Copy code

mov eax, var1 ; EAX = var1

add eax, var2 ; EAX = var1 + var2

mul var3 ; EDX:EAX = EAX * var3 (unsigned)

mov var4, eax ; var4 = lower 32 bits of product

✅ After MUL, EAX holds the lower 32 bits of the result.


✅ You can check Overflow if EDX ≠ 0 (means result didn't fit in 32 bits).

That wraps up 7.3.6 — you now know how to build arithmetic expressions in Assembly with full
control and safety!
📘 7.3.7 Section Review – Questions and Answers (Easy Wording)

1. Q: Why can’t overflow happen when MUL and one-operand IMUL instructions are used?
A: Because the result (product) is stored in two registers, which gives double the space. So, even if
the numbers are big, the result fits without overflow.

2. Q: How is one-operand IMUL different from MUL in creating the result?


A: IMUL is used for signed numbers, and it keeps the sign of the result. MUL is for unsigned
numbers, so it doesn't care about the sign.

3. Q: When does the one-operand IMUL set the Carry and Overflow flags?
A: If the upper half of the result is not a copy of the sign bit (not a correct sign extension), the flags
are set. This means the result is too big to fit in the lower part alone.

4. Q: If EBX is used in a DIV instruction, where is the answer (quotient) stored?


A: The answer (quotient) goes into EAX.

5. Q: If BX is used in a DIV instruction, where is the answer (quotient) stored?


A: The quotient is stored in AX.

6. Q: If BL is used in a MUL instruction, which register(s) get the result?


A: The result is saved in AX, because it's multiplying 8-bit values.

7. Q: Show an example of sign extending before using IDIV with a 16-bit number.
A:

assembly

Copy code

mov ax, -50 ; load -50 into AX

cwd ; sign-extend AX into DX:AX

mov bx, 5 ; divisor is 5

idiv bx ; signed divide DX:AX by BX

Here, cwd makes sure the sign of AX is correctly extended into DX, which is needed for signed
division.
Notes on Extended Addition and Subtraction

Overview: Extended addition and subtraction in assembly language allows for operations on integers
that exceed the processor's native word size, such as adding and subtracting integers larger than 32-
bits (e.g., 64-bit integers). This is achieved using the ADC (Add with Carry) and SBB (Subtract with
Borrow) instructions, which work across multiple bytes or words.

7.4 Extended Addition and Subtraction

Definition:

 Extended addition and subtraction refer to adding or subtracting numbers of very large sizes
(e.g., 1024-bit integers), which cannot be handled by standard operators in high-level
languages like C++. Assembly language provides low-level instructions (ADC and SBB) that
enable such operations.

7.4.1 ADC (Add with Carry) Instruction

Purpose:

 The ADC instruction adds the source operand along with the Carry flag to the destination
operand.

 It supports addition of multi-byte values (e.g., adding 64-bit integers) by adding each
byte/word individually and taking the carry from one operation to the next.

Format:

nginx

Copy code

ADC reg, reg

ADC mem, reg

ADC reg, mem

ADC mem, imm

ADC reg, imm

Example: Adding two 8-bit integers FFh + FFh:

assembly

Copy code

mov dl, 0 ; Clear DL register

mov al, 0FFh ; AL = 0FFh

add al, 0FFh ; AL = FEh, Carry flag set


adc dl, 0 ; Add AL + Carry flag to DL

 AL = FEh (result of 0FFh + 0FFh)

 DL:AL = 01FEh (16-bit result)

64-bit Addition Example:

assembly

Copy code

mov edx, 0

mov eax, 0FFFFFFFFh ; First 32-bit integer

add eax, 0FFFFFFFFh ; Add second 32-bit integer (AL = FEh)

adc edx, 0 ; Add carry from lower part to EDX

This results in EDX:EAX = 00000001FFFFFFFEh (64-bit sum).

7.4.2 Extended Addition Example

Extended_Add Procedure: The Extended_Add procedure adds two extended integers stored as
arrays of bytes. It uses a loop to add the corresponding bytes, incorporating the carry from each
addition into the next one.

Procedure Breakdown:

assembly

Copy code

Extended_Add PROC

pushad

clc ; Clear Carry flag

L1:

mov al, [esi] ; Load byte from first integer

adc al, [edi] ; Add corresponding byte from second integer + carry

pushfd ; Save flags (Carry)

mov [ebx], al ; Store result in sum

add esi, 1 ; Move to next byte of first integer

add edi, 1 ; Move to next byte of second integer

add ebx, 1 ; Move to next byte in sum

popfd ; Restore Carry flag


loop L1 ; Continue until all bytes are processed

mov byte ptr [ebx], 0 ; Clear high byte of sum if necessary

adc byte ptr [ebx], 0 ; Add any remaining carry to high byte

popad

ret

Extended_Add ENDP

Steps:

1. Initialize registers and clear the Carry flag.

2. Loop through each byte of the two extended integers:

o Add the current byte of both integers and the carry.

o Save the result and move the pointers to the next byte.

3. If a carry is generated from the high-order byte, it is added to the sum's extra byte.

Example Use:

assembly

Copy code

.data

op1 BYTE 34h,12h,98h,74h,06h,0A4h,0B2h,0A2h

op2 BYTE 02h,45h,23h,00h,00h,87h,10h,80h

sum BYTE 9 dup(0)

.code

main PROC

mov esi, OFFSET op1

mov edi, OFFSET op2

mov ebx, OFFSET sum

mov ecx, LENGTHOF op1

call Extended_Add

; Display sum

mov esi, OFFSET sum

mov ecx, LENGTHOF sum

call Display_Sum
call Crlf

main ENDP

This produces the sum of the two 8-byte integers in sum.

7.4.3 SBB (Subtract with Borrow) Instruction

Purpose:

 The SBB instruction performs subtraction while considering the Carry flag as a borrow. It is
used in a similar way to ADC for multi-byte subtraction.

Example:

assembly

Copy code

mov edx, 7

mov eax, 1

sub eax, 2 ; EAX = FFFFFFFFh (borrow occurs)

sbb edx, 0 ; Subtract 0 and Carry flag from EDX

This results in EDX:EAX = 0000000700000001h, after subtracting 2 from 1.

Steps in Data Movement:

1. The lower 32-bits (EAX) are subtracted first, setting the Carry flag.

2. The SBB instruction subtracts from the upper 32-bits (EDX), including the Carry flag.

Key Concepts for Extended Arithmetic:

1. Carry Flag in Extended Arithmetic:

o The Carry flag (CF) plays a crucial role in extended addition and subtraction. It is
carried over between iterations and may be added or subtracted from each byte of
the operands.

2. Handling Multiple Bytes:

o Extended arithmetic works by processing each byte or word of a large integer


sequentially, adding or subtracting each byte while considering the carry or borrow
from the previous operation.

3. Endianess:

o The integers involved in extended arithmetic are typically stored in little-endian


format, where the least significant byte comes first.

4. Stack for Saving and Restoring Flags:


o The Carry flag is saved on the stack before each iteration of the loop and restored
after each iteration, ensuring that the correct carry value is used for each step.

Conclusion:

 Extended Addition: Uses the ADC instruction to add multi-byte integers while managing
carries between operations.

 Extended Subtraction: Uses the SBB instruction to subtract multi-byte integers while
managing borrows.

 The procedures for extended arithmetic are designed to handle arbitrary-sized integers by
processing each byte or word individually while correctly managing carries and borrows
across multiple steps.

Section review 4
Describe the ADC instruction:

The ADC (Add with Carry) instruction adds two values along with the Carry flag. The Carry flag stores
whether a previous addition or subtraction resulted in a carry or borrow. When you use ADC, it not
only adds the two operands (like a regular addition) but also considers the Carry flag, adding it to the
result. This is used in operations like extended precision arithmetic, where multiple bytes are added
one after another, ensuring the Carry flag is correctly handled in each step.

Example:
If you have a Carry flag from a previous addition, the ADC instruction will add that Carry flag value (1
or 0) to the result of the current addition.

2. Describe the SBB instruction:

The SBB (Subtract with Borrow) instruction subtracts a value along with the Carry flag from a
destination operand. It is the opposite of ADC, meaning it considers whether a previous subtraction
resulted in a borrow. If the Carry flag is set, it subtracts 1 in addition to the source operand.

Example:
If you're subtracting two values, and a borrow occurred during a previous subtraction, SBB will
subtract that borrow (1 or 0) from the result.

3. What will be the values of EDX:EAX after the following instructions execute?

asm

Copy code

mov edx, 10h ; EDX = 10h (16 in decimal)

mov eax, 0A0000000h ; EAX = 0A0000000h

add eax, 20000000h ; Add 20000000h to EAX

adc edx, 0 ; Add Carry flag (if set) to EDX

Execution:
 EAX = 0A0000000h + 20000000h = C0000000h

 Since there’s no Carry from the ADD instruction (the result doesn't exceed the maximum
value of EAX), ADC doesn't add anything to EDX.

Final values:

 EAX = C0000000h

 EDX = 10h (unchanged)

4. What will be the values of EDX:EAX after the following instructions execute?

asm

Copy code

mov edx, 100h ; EDX = 100h (256 in decimal)

mov eax, 80000000h ; EAX = 80000000h

sub eax, 90000000h ; Subtract 90000000h from EAX

sbb edx, 0 ; Subtract Carry flag (if set) from EDX

Execution:

 EAX = 80000000h - 90000000h = FFFFFFFFh (because the result is negative, we get a borrow).

 The SBB instruction then subtracts 1 (because of the borrow) from EDX.

Final values:

 EAX = FFFFFFFFh

 EDX = FFh (because of the borrow)

5. What will be the contents of DX after the following instructions execute (STC sets the Carry
flag)?

asm

Copy code
mov dx, 5 ; DX = 5

stc ; Set Carry flag

mov ax, 10h ; AX = 10h (16 in decimal)

adc dx, ax ; Add AX and Carry flag to DX

Execution:

 DX = 5

 AX = 10h (16 in decimal)

 Since the Carry flag is set (because STC was used), ADC adds both AX and the Carry flag (1).

 DX = 5 + 16 + 1 = 22 (16 in decimal = 16h)


Final value:

 DX = 16h (22 in decimal)

You might also like