0% found this document useful (0 votes)
25 views75 pages

COAL v2.0

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

COAL v2.0

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

Karachi Institute of Economics & Technology

College of Computing & Information Sciences

Computer Organization &


Assembly Language
Lab Manual

Compiled by: Shahrukh Shakeel


Karachi Institute of Economics & Technology
College of Computing & Information Sciences

Computer Organization &


Assembly Language
Lab Manual
Compiled by:
Shahrukh Shakeel

CID: ______________ Semester: ______________


Student ID: ________________________________
Student Name: _____________________________
Instructor Name: ___________________________
KARACHI INSTITUTE OF ECONOMICS & TECHNOLOGY
College of Computing & Information Sciences
Computer Organization & Assembly Language Lab
Manual

INDEX
Lab Obtained
Date Particulars Instructor Marks
Signature
Lab 1: Introduction to Irvine Library and installation

Lab 2: Assembly Language Fundamentals I

Lab 3: Assembly Language Fundamentals II

Lab 4: Conditional Statements & Assembly Language Directives

Lab 5: Iterative Statements (While Loop & Nested Loop)

Lab 6: DUP Operator and Arrays in Assembly Language

Lab 7: Assembly Language Stack Memory & Arrays

Lab 8: Assembly Language Procedures

Lab 9: Assembly Floating Point Unit Stack

Lab 10: Conditional Loop

Lab 11: Integer Arithmetic and Bit Manipulation

Lab 12: Stack Memory & its Parameters & Advance Procedures

Lab 13: Recursion in Assembly Language


Contents
LAB 1 Introduction to Irvine Library and installation .................................................................................... 8
Microsoft Visual Studio 2010 Configuration ............................................................................................. 8
Next: Install the Book's Example Programs .......................................................................................... 8
Setting up Visual Studio ............................................................................................................................ 9
Building a Sample Assembly Language Program .................................................................................. 9
Lab 1- Exercise: ....................................................................................................................................... 10
LAB 2 Assembly Language Fundamentals I ................................................................................................ 11
1. Sample CODE: ..................................................................................................................................... 11
2. Data Representation ........................................................................................................................... 11
3. Segments:............................................................................................................................................ 11
4. Data Registers ..................................................................................................................................... 12
5. Some Irvine Pre-Define Functions: ..................................................................................................... 12
6. Multiplication and Division Instructions: ............................................................................................ 14
Lab 2- Exercise: ........................................................................................................................................... 18
LAB 3 Assembly Language Fundamentals II .............................................................................................. 19
1. Identifiers: ........................................................................................................................................... 19
2. Defining Data & Intrinsic Data Types: ................................................................................................. 19
3. Directives: ........................................................................................................................................... 19
4. Instructions: ........................................................................................................................................ 20
5. Assembling, Linking, and Running Programs: ..................................................................................... 22
6. User Input in Assembly Language: ...................................................................................................... 23
Lab 3- Exercise: ........................................................................................................................................... 23
LAB 4 Conditional Statements & Assembly Language Directives .............................................................. 24
1. Defining Strings: .................................................................................................................................. 24
2. Defining WORD and SWORD Data: ..................................................................................................... 24
3. Conditions: .......................................................................................................................................... 26
LAB 5 Iterative Statements (While Loop) .................................................................................................. 30
1. Assembly Language .While Loop: ....................................................................................................... 30
2. Nested .While loop in Assembly Language: ........................................................................................ 31
Lab 5- Exercise: ........................................................................................................................................... 32
LAB 6 DUP Operator and Arrays in Assembly Language ............................................................................ 33
1. DUP Operator:..................................................................................................................................... 33
2. Arrays of Words: ................................................................................................................................. 33
3. Defining DWORD and SDWORD Data: ................................................................................................ 33
4. Array of Doublewords: ........................................................................................................................ 33
5. Defining QWORD Data: ....................................................................................................................... 34
6. Symbolic Constants: ............................................................................................................................ 34
6.1. Equal-Sign Directive: ................................................................................................................... 34
6.2. Calculating the Sizes of Arrays and Strings: ................................................................................ 34
6.3. EQU Directive: ............................................................................................................................. 35
6.4. TEXTEQU Directive: ..................................................................................................................... 36
Lab 6- Exercise: ........................................................................................................................................... 37
LAB 7 Assembly Language Stack Memory & Arrays ................................................................................... 38
1. LENGTHOF Operator: .......................................................................................................................... 38
2. SIZEOF Operator:................................................................................................................................. 38
3. Neg Instruction: .................................................................................................................................. 39
4. Stack Memory: .................................................................................................................................... 39
5. Random32: .......................................................................................................................................... 40
6. RandomRange: .................................................................................................................................... 40
7. Randomize: ......................................................................................................................................... 41
8. ReadChar & WriteChar:....................................................................................................................... 41
9. ReadHex & WriteHex: ......................................................................................................................... 42
10. INCREMENT (Inc):............................................................................................................................ 42
11. DECREMENT (Dec): ......................................................................................................................... 42
12. EXCHANGE (xchg): ........................................................................................................................... 42
13. movzx Instruction:........................................................................................................................... 43
14. movsx Instruction:........................................................................................................................... 43
Lab 7- Exercise: ........................................................................................................................................... 43
LAB 8 Assembly Language Procedures ...................................................................................................... 44
1. Assembly Procedures: ......................................................................................................................... 44
2. Nested Procedure Call: ....................................................................................................................... 46
Lab 8- Exercise: ........................................................................................................................................... 46
LAB 9 Assembly Floating Point Unit Stack ................................................................................................. 47
1. FPU Register Stack .............................................................................................................................. 47
2. Load Floating Point Instruction (FLD):................................................................................................. 47
3. Reading and Writing Floating-Point Values ........................................................................................ 48
4. ShowFPUStack procedure ................................................................................................................... 48
5. fstp instruction .................................................................................................................................... 49
6. finit instruction.................................................................................................................................... 49
7. READING & WRITING STRING: ............................................................................................................ 50
Lab 9- Exercise: ........................................................................................................................................... 50
LAB 10 Conditional LOOP .......................................................................................................................... 51
1. LOOPZ and LOOPE Instruction: ........................................................................................................... 51
2. LOOPNZ and LOOPNE Instruction: ...................................................................................................... 52
3. Block -Structured IF Statements Structured IF Statements: ............................................................... 53
4. Compound Expression with AND [1/3] Compound Expression with AND [1/3]: ................................ 53
5. Compound Expression with AND [2/3] Compound Expression with AND [2/3]: ................................ 54
6. Compound Expression with AND [3/3]: .............................................................................................. 54
7. Compound Expression with OR [1/2]:................................................................................................. 55
8. Compound Expression with OR [2/2]:................................................................................................. 55
9. WHILE Loop: ........................................................................................................................................ 55
Lab 10- Exercise: ......................................................................................................................................... 55
LAB 11 Integer Arithmetic and Bit Manipulation ....................................................................................... 56
1. Bitwise Logical Instructions:................................................................................................................ 56
2. Shift and Rotate Instructions: ............................................................................................................. 56
3. SHLD and SHRD Instructions: .............................................................................................................. 57
4. Binary Multiplication and Division: ..................................................................................................... 58
5. Converting a Number to ASCII Hexadecimal Format: ......................................................................... 58
6. Convert2Bin procedure:...................................................................................................................... 60
7. Integer Multiplication and Division:.................................................................................................... 61
8. MUL and IMUL Instructions: ............................................................................................................... 61
9. DIV and IDIV Instructions: ................................................................................................................... 61
10. CBW, CWD, and CDQ Instructions: ................................................................................................. 62
11. Divide Overflow: ............................................................................................................................. 62
12. Converting an Unsigned Integer to ASCII Decimal Format: ............................................................ 62
13. Extended Addition .......................................................................................................................... 63
14. Extended Subtraction:: .................................................................................................................... 63
LAB 12 Stack Memory & It’s Parameters & Advance Procedures ............................................................. 64
1. Stack Parameters: ............................................................................................................................... 64
4. Cleaning up the Stack Parameters with the RET Instruction: ............................................................. 65
5. Saving and Restoring Registers: .......................................................................................................... 65
6. The EBP Register: ................................................................................................................................ 65
7. Passing Parameters by Value and by Reference: ................................................................................ 66
8. Local Variables and Stack Frames: ...................................................................................................... 67
9. Stack Frame:........................................................................................................................................ 69
10. Returning the Result of a Procedure: ............................................................................................. 69
11. PROTO and PROC Directives: .......................................................................................................... 70
12. INVOKE Directive:............................................................................................................................ 71
13. LOCAL Directive:.............................................................................................................................. 71
14. USES Directive: ................................................................................................................................ 71
Lab 12- Exercise: ......................................................................................................................................... 72
LAB 13 Recursion in Assembly Language .................................................................................................. 73
1. Recursive Procedure: .......................................................................................................................... 73
1.1. EBP Registers:.............................................................................................................................. 73
1.2. ESP Registers: .............................................................................................................................. 73
Lab 13- Exercise: ......................................................................................................................................... 74
LAB 1
Introduction to Irvine Library and installation
Microsoft Visual Studio 2010 Configuration
Getting Started with MASM and Visual Studio 2010

This Lab shows you how to set up Visual Studio 2010 (including the Express version) to
work with Microsoft MASM.

Using Visual Studio Express? You must do the following in order to see the same menu
options as the users of Visual Studio professional: from the Tools menu, select Settings,
and select Expert Settings.
Next: Install the Book's Example Programs

The examples are stored in a self-extracting archive file that automatically extracts to
the c:\Irvine folder. Unless you have some objection to using that location, do not alter the
path. (Lab managers: you can designate c:\Irvine directory as read-only.).

The following files will be copied into the c:\Irvine directory:

Filename Description

cmd.exe Shortcut to the Windows command-line interpreter (named cmd.exe)

GraphWin.inc Include file for writing Windows applications

Irvine16.inc Include file used with the Irvine16 link library (16-bit applications)

Irvine16.lib 16-bit link function library used with this book

Irvine32.inc Include file used with the Irvine32 link library (32-bit applications)

Link16.exe 16-bit linker

Irvine32.lib 32-bit link function library used with this book

User32.lib Basic I/O link library

Macros.inc Include file containing macros (explained in Chapter 10)

SmallWin.inc Small-sized include file, used by Irvine32.inc


make16.bat Batch file for building 16-bit applications

VirtualKeys.inc Keyboard code definitions file, used by Irvine32.inc

A subdirectory named Examples will contain all the example programs shown in the book,
as well as all the source code for the book's 16- and 32-bit link libraries.

Setting up Visual Studio


Building a Sample Assembly Language Program
Now you're ready to open and build your first project.
Opening a Project
Visual Studio and Visual Studio Express require assembly language source files to belong to
a project, which is a kind of container. A project holds configuration information such as the
locations of the assembler, linker, and required libraries. A project has its own folder, and it
holds the names and locations of all files belonging to it.
Do the following steps, in order:
1. Open the visual studio and create a new Project.
2. Select the Other languages and select the C++ language and create the console
project Application.
3. Create the project name with no extension.
4. Now go to the project and right click on project and select the option Build
Customization and select it and check the MASM and click OK Button.
5. Now create a new file in project with the extension of (file_name.asm).
6. Go to the project Properties and check first in the List and check Microsoft Macro
Assembler is Appear in the list or not if yes so go forward.
7. Now go to the linker general property and select the Additional Libraries Directories
and select the Irvine Folder.
8. Now go to the linker input section and select the property Additional Dependencies
and include the file Irvine32.lib.
9. Now go to Microsoft Macro Assembler and select the property Include Path and
define the path of Irvine Directory.

EXAMPLE: You should write the following program in the editor window:

CODE:
INCLUDE Irvine32.inc
.data
myMessage BYTE "Hello World of Assembly Language",0dh,0ah,0
.code
main PROC
call Clrscr
mov edx,OFFSET myMessage
call WriteString
exit
main ENDP
END main

RUN THE PROGRAM:


Select Start without Debugging from the Debug menu. The following console window
should appear, although your window will be larger than the one shown here:

OUTPUT:

The "Press any key to continue..." message is automatically generated by Visual Studio.
Congratulations, you have just run your first Assembly Language program.
Press any key to close the Console window.

Lab 1- Exercise:
LAB 2
Assembly Language Fundamentals I

1. Sample CODE:
INCLUDE Irvine32.inc
.data
.code
main PROC
mov eax,5 ; move 5 to the EAX register
add eax,6 ; add 6 to the EAX register
call WriteInt ; display value in EAX
exit ; quit
main ENDP
END main

2. Data Representation
If no radix is given, the integer constant is assumed to be decimal. Here are some examples
using different radixes:

Common radix characters:


1. h – hexadecimal
2. d – decimal
3. b – binary
4. r – encoded real

Example:
30d, 6Ah, 42, 1101b
• Hexadecimal beginning with letter must have leading 0: 0A5h ƒ
• If no radix is given, the integer constant is assumed to be decimal

3. Segments:
Following are some directives that are widely used in assembly language programs:
1. The .DATA directive identifies the area of a program containing variables:
.data
2. The .CODE directive identifies the area of a program containing executable
instructions:
.code
3. The .STACK directive identifies the area of a program holding the runtime stack,
setting its size: .stack 1000h
4. Data Registers
Four 32-bit data registers are used for arithmetic, logical, and other operations. These 32-
bit registers can be used in three ways −
• As complete 32-bit data registers: EAX, EBX, ECX, EDX.
• Lower halves of the 32-bit registers can be used as four 16-bit data registers: AX,
BX, CX and DX.
• Lower and higher halves of the above-mentioned four 16-bit registers can be used
as eight 8-bit data registers: AH, AL, BH, BL, CH, CL, DH, and DL.

Figure 1.1
Some of these data registers have specific use in arithmetical operations.

AX is the primary accumulator: it is used in input/output and most arithmetic instructions. For
example, in multiplication operation, one operand is stored in EAX or AX or AL register according to the
size of the operand.

BX is known as the base register: as it could be used in indexed addressing.

CX is known as the count register: as the ECX, CX registers store the loop count in iterative
operations.

DX is known as the data register: It is also used in input/output operations. It is also used with AX
register along with DX for multiply and divides operations involving large values.

5. Some Irvine Pre-Define Functions:


There are many pre define function Irvine gives us but we use functions as per requirement:

1. Call WriteINT/WriteBin/WriteDec/WriteHex: To display the EAX register value


we us it.

Example 1: Adding two integers:

CODE:
INCLUDE Irvine32.inc
.code
main PROC
mov eax,10000h ; EAX = 10000h
add eax,40000h ; EAX = 50000h
call DumpRegs ; display registers
exit
main ENDP
END main

Example 1: Program Explanations


1. INCLUDE Irvine32.inc
The INCLUDE directive copies necessary definitions and setup information
from a text file named Irvine32.inc, located in the assembler’s INCLUDE
directory.
2. .code
The .code directive marks the beginning of the code segment, where all executable
statements ina program are located.
3. main PROC
The PROC directive identifies the beginning of a procedure. The name chosen for the
only procedure in our program is main.
4. mov eax,10000h ; EAX = 10000h
The MOV instruction moves (copies) the integer 10000h to the EAX register. The
first operand (EAX) is called the destination operand, and the second operand is
called the source operand. The comment on the right side shows the expected new
value in the EAX register.
5. add eax,40000h ; EAX = 50000h
The ADD instruction adds 40000h to the EAX register. The comment shows the
expected new value in EAX.
6. sub eax,20000h ; EAX = 30000h
The SUB instruction subtracts 20000h from the EAX register.
7. Call DumpRegs ; display registers
The CALL statement calls a procedure that displays the current values of the CPU
registers. This can be a useful way to verify that a program is working correctly.
8. main ENDP
The exit statement (indirectly) calls a predefined MS-Windows function that halts
the program. The ENDP directive marks the end of the main procedure. Note that
exit is not a MASM keyword; instead, it’s a macro command defined in the
Irvine32.inc include file that provides a simple way to end a program.
9. END main
The END directive marks the last line of the program to be assembled. It identifies
the name of the program’s startup procedure (the procedure that starts the program
execution.
6. Multiplication and Division Instructions:
In 32-bit mode, integer multiplication can be performed as a 32-bit, 16-bit, or 8-bit
operation. In 64-bit mode, you can also use 64-bit operands. The MUL and IMUL
instructions perform unsigned and signed integer multiplication, respectively. The DIV
instruction performs unsigned integer division, and IDIV performs signed integer division.

6.1. MUL Instruction:


In 32-bit mode, the MUL (unsigned multiply) instruction comes in three versions: The first
version multiplies an 8-bit operand by the AL register. The second version multiplies a 16-
bit operand by the AX register, and the third version multiplies a 32-bit operand by the EAX
register. The multiplier and multiplicand must always be the same size, and the product is
twice their size. The three formats accept register and memory operands, but not
immediate operands:

Syntax:
MUL reg/mem8
MUL reg/mem16
MUL reg/mem32

The single operand in the MUL instruction is the multiplier. Table 7-2 shows the default
multiplicand and product, depending on the size of the multiplier. Because the destination
operand is twice the size of the multiplicand and multiplier, overflow cannot occur. MUL
sets the Carry and Overflow flags if the upper half of the product is not equal to zero. The
Carry flag is ordinarily used for unsigned arithmetic, so we’ll focus on it here. When AX is
multiplied by a 16-bit operand, for example, the product is stored in the combined DX and
AX registers. That is, the high 16 bits of the product are stored in DX, and the low 16 bits
are stored in AX. The Carry flag is set if DX is not equal to zero, which lets us know that the
product will not fit into the lower half of the implied destination operand.

Example:
The following statements multiply 12345h by 1000h, producing a 64-bit product in the
combined EDX and EAX registers. The Carry flag is clear because the upper half of the
product in EDX equals zero:
CODE:
mov eax,12345h
mov ebx,1000h
mul ebx ; EDX:EAX = 0000000012345000h, CF = 0

The following diagram illustrates the movement between registers:

6.2. IMUL Instruction:


The IMUL (signed multiply) instruction performs signed integer multiplication. Unlike the
MUL instruction, IMUL preserves the sign of the product. It does this by sign extending the
highest bit of the lower half of the product into the upper bits of the product. The x86
instruction set supports three formats for the IMUL instruction: one operand, two
operands, and three operands. In the one-operand format, the multiplier and multiplicand
are the same size and the product is twice their size.

6.2.1. Single-Operand Formats:


The one-operand formats store the product in AX, DX:AX, or EDX:EAX:

IMUL reg/mem8 ; AX = AL * reg/mem8


IMUL reg/mem16 ; DX:AX = AX * reg/mem16
IMUL reg/mem32 ; EDX:EAX = EAX * reg/mem32

6.2.2. Two-Operand Formats (32-Bit Mode):


The two-operand version of the IMUL instruction in 32-bit mode stores the product in the
first operand, which must be a register. The second operand (the multiplier) can be a
register, a memory operand, or an immediate value. Following are the 16-bit formats:

IMUL reg16,reg/mem16
IMUL reg16,imm8
IMUL reg16,imm16

Following are the 32-bit operand types showing that the multiplier can be a 32-bit register,
a 32-bit memory operand, or an immediate value (8 or 32 bits):

IMUL reg32,reg/mem32
IMUL reg32,imm8
IMUL reg32,imm32

The two-operand formats truncate the product to the length of the destination. If
significant digits are lost, the Overflow and Carry flags are set. Be sure to check one of these
flags after performing an IMUL operation with two operands.
6.2.3. Three-Operand Formats:
The three-operand formats in 32-bit mode store the product in the first operand. The
second operand can be a 16-bit register or memory operand, which is multiplied by the
third operand, an 8- or 16-bit immediate value:

IMUL reg16,reg/mem16,imm8
IMUL reg16,reg/mem16,imm16

A 32-bit register or memory operand can be multiplied by an 8- or 32-bit immediate value:

IMUL reg32,reg/mem32,imm8
IMUL reg32,reg/mem32,imm32

If significant digits are lost when IMUL executes, the Overflow and Carry flags are set. Be
sure to check one of these flags after performing an IMUL operation with three operands.

Example: IMUL
The following instructions multiply 48 by 4, producing 192 in AX. Although the product is
correct, AH is not a sign extension of AL, so the Overflow flag is set:
CODE:
mov al,48
mov bl,4
imul bl ; AX = 00C0h, OF = 1

The following instructions multiply 4 by 4, producing 16 in AX. AH is a sign extension of AL,


so the Overflow flag is clear:

mov al,-4
mov bl,4
imul bl ; AX = FFF0h, OF = 0

The following instructions multiply 48 by 4, producing 192 in DX:AX. DX is a sign extension


of AX, so the Overflow flag is clear:

mov ax,48
mov bx,4
imul bx ; DX:AX = 000000C0h, OF = 0

The following instructions perform 32-bit signed multiplication (4,823,424 * 423),


producing 2,040,308,352 in EDX:EAX. The Overflow flag is clear because EDX is a sign
extension of EAX:

mov eax,+4823424
mov ebx,-423
imul ebx ; EDX:EAX = FFFFFFFF86635D80h, OF = 0
The following instructions demonstrate two-operand formats:
CODE:
.data
word1 SWORD 4
dword1 SDWORD 4
.code
mov ax,-16 ; AX = -16
mov bx,2 ; BX = 2
imul bx,ax ; BX = -32
imul bx,2 ; BX = -64
imul bx,word1 ; BX = -256
mov eax,-16 ; EAX = -16
mov ebx,2 ; EBX = 2
imul ebx,eax ; EBX = -32
imul ebx,2 ; EBX = -64
imul ebx,dword1 ; EBX = -256

The two-operand and three-operand IMUL instructions use a destination operand that is
the same size as the multiplier. Therefore, it is possible for signed overflow to occur.
Always check the Overflow flag after executing these types of IMUL instructions. The
following two-operand instructions demonstrate signed overflow because 64,000 cannot
fit within the 16-bit destination operand:

mov ax,-32000
imul ax,2 ; OF = 1

6.3. DIV Instruction:


In 32-bit mode, the DIV (unsigned divide) instruction performs 8-bit, 16-bit, and 32-bit
unsigned integer division. The single register or memory operand is the divisor. The
formats are:

DIV reg/mem8
DIV reg/mem16
DIV reg/mem32

The following table shows the relationship between the dividend, divisor, quotient, and
remainder:
In 64-bit mode, the DIV instruction uses RDX:RAX as the dividend, and it permits the
divisor to be a 64-bit register or memory operand. The quotient is stored in RAX, and the
remainder in RDX.

Example: Dividing Integers

CODE:
INCLUDE Irvine32.inc
.data
.code
main PROC
mov eax,10
mov ebx,2
sub edx,edx
div ebx
call writeDec
call dumpregs
exit
main ENDP
END main

Lab 2- Exercise:
LAB 3
Assembly Language Fundamentals II

1. Identifiers:
Identifiers – a programmer-choice name

✓ 1-247 characters, including digits


✓ not case sensitive
✓ The first character must be a letter (A..Z, a..z), underscore (_), @, ?, or $. Subsequent
character may also be digits.
✓ An identifier cannot be the same as an assembler reserved word.

Examples:
✓ var1,
✓ Count,
✓ $first,
✓ _main,
✓ MAX ,
✓ open_file, xVal

2. Defining Data & Intrinsic Data Types:


✓ Intrinsic Data Types:
o BYTE, SBYTE ƒ 8-bit unsigned integer; 8-bit signed integer
o WORD, SWORD 16-bit unsigned & signed integer
o DWORD, SDWORD ƒ 32-bit unsigned & signed integer
o QWORD ƒ 64-bit integer
o TBYTE ƒ 80-bit integer
o REAL4 ƒ 4-byte IEEE short real
o REAL8 ƒ 8-byte IEEE long real
o REAL10 ƒ 10-byte IEEE extended real

3. Directives:
Commands that are recognized and acted upon by the assembler.
✓ Not part of the Intel instruction set
✓ Directives do not execute at run time, whereas instructions do.
✓ Used to declare code, data areas, select memory model, declare procedures, etc.
✓ Not case sensitive: It recognizes .data, .DATA, and .Data as equivalent.

Example Code:
myVar DWORD 26 ; DWORD directive
mov ax, myVar ; MOV instruction

4. Instructions:
✓ An instruction is a statement that becomes executable when a program is
assembled.
✓ Instructions are translated by the assembler into machine language bytes, which are
loaded and executed by the CPU at run time.
✓ We use the Intel IA-32 instruction set

Syntax CODE:
[label] mnemonic operand(s) [;comment]
label ;optional
instruction mnemonic required: such as MOV, ADD, SUB, MUL
operands usually required

An instruction contains:

Labels (optional):
✓ Act as place markers
✓ marks the address (offset) of code and data
✓ Follow identifier rules

Data label:
✓ must be unique
✓ example: count (not followed by colon)
Count DWORD 100

Code Label:
✓ target of jump and loop instructions
✓ example: target: (followed by colon)
target:
MOV ax, bx

JMP target

Mnemonics (required):
✓ Instruction Mnemonics
✓ memory aid
✓ examples: MOV, ADD, SUB, MUL, CALL
MOV: Move (assign) one value to another
ADD: Add two values
SUB: Subtract one value from another
MUL: Multiply two values
JMP: Jump to a new location
CALL: Call a procedure

Operands (depends on the instruction):


✓ Assembly language instructions can have between zero and three operands, each of
which can be a register, memory operand, constant expression, or I/O port.
✓ constant (immediate value): ex. 96
✓ constant expression: ex. 10 * 10
✓ register: ex. Eax
✓ memory (data label): ex. Count

Examples:
Example of assembly language instructions having varying numbers of operands:
No operands Code:
stc ; set Carry flag

One operands Code:


inc eax ; register
inc myByte ; memory

Two operands Code:


add ebx, ecx ; register, register
sub myByte, 25 ; memory, constant
add eax,36 * 25 ; register, constant-expression

Comments (optional):

✓ Comments can be specified in two ways: single-line and block comments.

Single-Line comments:

✓ Begin with semicolon (;)

Multi-Line comments:

✓ Begin with COMMENT directive and a programmer-chosen character


✓ End with the same programmer-chosen character
Example:
COMMENT!
This is a comment.
This line is also a comment.
! We can also use any other symbol:
COMMENT &

Example: Adding Three Integers:


CODE:
INCLUDE Irvine32.inc
.code
main PROC
mov eax,10000h ; EAX = 10000h
add eax,40000h ; EAX = 50000h
sub eax,20000h ; EAX = 30000h
call DumpRegs
exit
main ENDP
END main

5. Assembling, Linking, and Running Programs:


1. The Assemble-Link-Execute Cycle:
✓ The following diagram describes the steps from creating a source program through
executing the compiled program
✓ If the source code is modified, Steps 2 through 4 must be repeated.

2. Listing File
✓ Use it to see how your program is compiled
✓ Contains:
o source code
o addresses
o object code (machine language)
o segment names
o symbols (variables, procedures, and constants)
✓ Example: addSub.lst

3. Map File
✓ Information about each program segment:
o starting address
o ending address
o size
o segment type
✓ Example: addSub.map (16-bit version, not generated in 32-bit version)

6. User Input in Assembly Language:


Some Irvine Pre-Define Functions:
There are many pre define function Irvine gives us but we use functions as per requirement:

1. Call WriteINT/WriteBin/WriteDec/WriteHex: To display the EAX register value we


us it.
2. Call ReadInt/ReadDec/ReadBin/ReadHex: This function is used to take user input
and pass the user input into eax register by default.

Example 2: Take user input and display it.


CODE:
INCLUDE Irvine32.inc
.data
myMessage1 BYTE "Enter the first number: ",0dh,0ah,0
myMessage1 BYTE "Enter the second number: ",0dh,0ah,0
.code
main PROC
mov edx,offset myMessage1
call WriteString
call ReadInt ;Reads the integer value from user and moves it to eax.
Call Writeint

mov edx,offset myMessage2


call WriteString
call ReadInt ;Reads the integer value from console and moves it to eax.
Call Writeint
exit
main ENDP
LAB 4
Conditional Statements & Assembly Language Directives

1. Defining Strings:
To define a string of characters, enclose them in single or double quotation marks. The
most common type of string ends with a null byte (containing 0).

Example:
greeting1 BYTE "Good afternoon",0
greeting2 BYTE 'Good night',0

Byte values must be separated by commas. Without that exception, greeting1 would have
to be defined as:

Example:
greeting1 BYTE 'G','o','o','d'....etc.

A string can be divided between multiple lines without having to supply a label for each
line:

Example:
greeting1 BYTE "Welcome to the Computer Organization "
BYTE "Lab",0dh,0ah
BYTE "If you have any query, contact "
BYTE "Admission deprt.",0dh,0ah,0

The hexadecimal codes 0Dh and 0Ah are alternately called CR/LF (carriage-return line-
feed) or end-of-line characters. When written to standard output, they move the cursor to
the left column of the line following the current line.

2. Defining WORD and SWORD Data:


The WORD (define word) and SWORD (define signed word) directives create storage for
one or more 16-bit integers:

Example:
word1 WORD 65535 ; largest unsigned value
word2 SWORD -32768 ; smallest signed value
word3 WORD ? ; Uninitialized, unsigned
Example: Sample Program for unsign word:

CODE:
INCLUDE Irvine32.inc
.data
value word 75
.code
main PROC
mov eax,0
mov ax,value
call writeint
call crlf
exit
main ENDP
END main
OR
INCLUDE Irvine32.inc
.data
value word 75
.code
main PROC
movzx eax,value
call writeint
call crlf
exit
main ENDP
END main

Example: Sample Program for sign word:

CODE:
INCLUDE Irvine32.inc
.data
value Sword -75
.code
main PROC
movsx eax,value
call writeint
call crlf
exit
main ENDP
END main
3. Conditions:
Conditional execution in assembly language is accomplished by several looping and
branching instructions. These instructions can change the flow of control in a program.
Conditional execution is observed in two scenarios:
S:No Conditional Instructions

Unconditional jump
This is performed by the JMP instruction. Conditional execution often
1 involves a transfer of control to the address of an instruction that does
not follow the currently executing instruction. Transfer of control may
be forward, to execute a new set of instructions or backward, to re-
execute the same steps.

Conditional jump
This is performed by a set of jump instructions j<condition>
2 depending upon the condition. The conditional instructions transfer
the control by breaking the sequential flow and they do it by changing
the offset value in IP.

NOTE: Let us discuss the CMP instruction before discussing the conditional instructions.

3.1. CMP Instruction:


The CMP instruction compares two operands. It is generally used in conditional execution.
This instruction basically subtracts one operand from the other for comparing whether the
operands are equal or not. It does not disturb the destination or source operands. It is used
along with the conditional jump instruction for decision making.

Syntax:
CMP destination, source

CMP compares two numeric data fields. The destination operand could be either in register
or in memory. The source operand could be a constant (immediate) data, register or
memory.
3.2. Unconditional Jump:
As mentioned earlier, this is performed by the JMP instruction. Conditional execution often
involves a transfer of control to the address of an instruction that does not follow the
currently executing instruction. Transfer of control may be forward, to execute a new set of
instructions or backward, to re-execute the same steps.

Syntax:
The JMP instruction provides a label name where the flow of control is transferred
immediately. The syntax of the JMP instruction is:
JMP label

Example: Unconditional jump:


CODE:
INCLUDE Irvine32.inc
.data
value Sword -75
.code
main PROC
MOV AX, 00 ; Initializing AX to 0
MOV BX, 00 ; Initializing BX to 0
MOV CX, 01 ; Initializing CX to 1
L20: ;Label
ADD AX, 01 ; Increment AX
ADD BX, AX ; Add AX to BX
SHL CX, 1 ; shift left CX, this in turn doubles the CX value
JMP L20 ; repeats the statements
exit
main ENDP

3.3. Conditional Jump:


If some specified condition is satisfied in conditional jump, the control flow is transferred
to a target instruction. There are numerous conditional jump instructions depending upon
the condition and data.
Following are the conditional jump instructions used on signed data used for arithmetic
operations −
Example: Unconditional jump:
CODE:
INCLUDE Irvine32.inc
.data
.code
main proc
mov eax,6
cmp eax,6
jle L1
mov eax,10
L1:
mov eax,20
exit
main endp
end main

3.4. Loop Operator:


The processor instruction set, however, includes a group of loop instructions for
implementing iteration. The basic LOOP instruction has the following syntax:

Syntax:
LOOP label

Where, label is the target label that identifies the target instruction as in the jump
instructions. The LOOP instruction assumes that the ECX register contains the loop
count. When the loop instruction is executed, the ECX register is decremented and the
control jumps to the target label, until the ECX register value, i.e., the counter reaches the
value zero.

Example: Program to print the counting 1 to 10:


CODE:
INCLUDE Irvine32.inc
.data
.code
main proc
mov eax,0
mov ecx,10
label1:
inc eax
call writedec
call crlf
loop label1
exit
main endp
LAB 5
Iterative Statements (While Loop)

1. Assembly Language .While Loop:


Generates code that executes the block of statements while condition remains true.

Syntax:
.WHILE constantExpression
statements
.ENDW

Example: Program to print the Hello on 10 times:

CODE:
INCLUDE Irvine32.inc
.data
myMessage BYTE "Hello",0dh,0ah,0
search DWORD ?
.code
main PROC
call Clrscr
call ReadInt
mov search,eax
mov edx,offset myMessage
sub ecx,ecx
.while ecx <= search
call WriteString
inc ecx
.endw
exit
main ENDP
END main

Output:
2. Nested .While loop in Assembly Language:
Assembly language provides the nested loop in which one loop contains inside multiple
loops as shown:

Syntax:
.WHILE constantExpression
statements
.WHILE constantExpression
statements
.
.ENDW
.ENDW

Example:

Make a program that prints right angle triangle. In the below manner:
CODE:
INCLUDE Irvine32.inc
.data
msg1 BYTE"Enter a Number: ",0
num1 DWORD ?
ans DWORD ?

.code
main PROC
;// Prints msg1 while Reads into num1
mov edx, OFFSET msg1
call writestring
call readInt
mov num1,eax
mov ecx,0
mov ebx,1
.while ecx<num1 ;// This loop defines the length
mov eax,ecx
mov ebx,1

.while ebx<=ecx ;//This loop defines the breath


call writedec
inc ebx
.endw

call crlf
inc ecx
.endw
call crlf
call waitmsg
exit
main endp
end main

Output:

Lab 5- Exercise:
LAB 6
DUP Operator and Arrays in Assembly Language

1. DUP Operator:
Use DUP to allocate (create space for) an array or string. The DUP operator allocates
storage for multiple data items, using a constant expression as a counter. It is particularly
useful when allocating space for a string or array, and can be used with initialized or
uninitialized data:

Example:

BYTE 20 DUP(0) ; 20 bytes, all equal to zero


BYTE 20 DUP(?) ; 20 bytes, uninitialized
BYTE 4 DUP("STACK") ; 20 bytes: STACKSTACKSTACKSTACK"

2. Arrays of Words:
Create an array of words by listing the elements. The following array contains a list of
values:

Example:
myList WORD 1,2,3,4,5

3. Defining DWORD and SDWORD Data:


The DWORD (define doubleword) and SDWORD (define signed doubleword) directives
allocate storage for one or more 32-bit integers:
Example:
val1 DWORD 12345678h ; unsigned
val2 SDWORD -2147483648 ; signed

4. Array of Doublewords:
Create an array of doublewords by explicitly initializing each element, or use
the DUP operator. Here is an array containing specific unsigned values:

Example:
myList DWORD 1,2,3,4,5
5. Defining QWORD Data:
The QWORD (define quadword) directive allocates storage for 64-bit (8-byte) values:

Example:
quad1 QWORD 1234567812345678h

The legacy DQ directive can also be used:

Example:
quad1 DQ 1234567812345678h

6. Symbolic Constants:
Associate and identifier (a symbol) with an integer expression or some text:
✓ Symbols do not reserve storage.
✓ Used only by the assembler when scanning a program.
✓ Cannot change at run time.
✓ They are used only by the assembler when scanning a program.

6.1. Equal-Sign Directive:


This Equal-Sign Directive symbolic constant is defined as:

✓ expression is a 32-bit integer (expression or constant)


✓ may be redefined
✓ Name is called a symbolic constant.
Syntax:

Name = expression

Example:

COUNT = 500
..
mov al, COUNT

6.2. Calculating the Sizes of Arrays and Strings:


6.2.1. Calculating the Size of a Byte Array:

Current location counter: $


✓ Subtract address of list
✓ Difference is the number of bytes
Example:

list BYTE 10,20,30,40


ListSize = ($ - list)

Note: ListSize must follow immediately after List.

6.2.2. Calculating the Size of a Word Array:


Divide total number of bytes by 2 (the size of a word)

Example:

List WORD 1000h, 2000h, 3000h, 4000h


ListSize = ($ - list) / 2

6.2.3. Calculating the Size of a Doubleword Array:


Divide total number of bytes by 4 (the size of a word)

Example:

List WORD 1000h, 2000h, 3000h, 4000h


ListSize = ($ - list) / 4

6.3. EQU Directive:


EQU Directive can be define as:

✓ Define a symbol as either an integer or text expression.


✓ Cannot be redefined

Syntax:

name EQU expression ; integer expression


name EQU symbol ; existing symbol name
name EQU ; any text

Example:

.data
Prompt BYTE pressKey
MI WORD matrix
.code
matrix EQU 10 * 10
PI EQU pressKey EQU <"Press any key to continue...",0
6.4. TEXTEQU Directive:
TEXTEQU Directive can be define as:

✓ Define a symbol as either an integer or text expression.


✓ Called a text macro
✓ Can be redefined

There are three different formats:

✓ the first assigns text


✓ the second assigns the contents of an existing text macro
✓ and the third assigns a constant integer expression:

Syntax:

– name TEXTEQU <text>


– name TEXTEQU textmacro
– name TEXTEQU %constExpr

Example:
.data
continueMsg TEXTEQU <"Do you wish to continue (Y/N)?">
rowSize = 5
.data
prompt1 BYTE continueMsg
count TEXTEQU %(rowSize * 2) ; evaluates the expression
setupAL TEXTEQU <mov al,count>
.code
setupAL ; generates: "mov al,10"

Example: Sample program to take 5 inputs from user and print them:
CODE:
INCLUDE Irvine32.inc
.data
array Byte 50 DUP (0)
message1 byte "Enter the 5 number:"
.code
main PROC
mov edx,offset message1
call writestring
mov ecx,0
.while (ecx < 5)
call readdec
mov array[ecx],al
inc ecx
.endw
call crlf
mov ecx,0
.while (ecx < 5)
mov al,array[ecx]
call writedec
call crlf
inc ecx
.endw
exit
main ENDP
END main

OUTPUT:

Lab 6- Exercise:
LAB 7
Assembly Language Stack Memory & Arrays

1. LENGTHOF Operator:
The LENGTHOF operator counts the number of elements in an array.

Example:
.data

byte1 BYTE 10,20,30


array1 WORD 30 DUP(?),0,0
array2 WORD 5 DUP(3 DUP(?))
array3 DWORD 1,2,3,4
array4 BYTE "12345678",0

.code
mov eax , lengthof byte1 ; eax = 3
call writeint
mov eax , lengthof array1 ; eax = 32
call writeint
mov eax , lengthof array2 ; eax = 15
call writeint
mov eax , lengthof array3 ; eax = 4
call writeint
mov eax , lengthof array4 ; eax = 9
call writeint

2. SIZEOF Operator:
The SIZEOF operator returns a value that is equivalent to multiplying LENGTHOF by TYPE.
In the following example, Array has TYPE 2 and LENGTHOF 32. Therefore, SIZEOF Array
equals 64:

Example:
.data
Array WORD 32 DUP(0)
.code
mov eax, SIZEOF Array ; EAX = 64
call writeint
3. Neg Instruction:
Neg instruction changes the sign of value.

Example:
.data
value SDWORD 10
.code
main proc
mov eax, value
neg eax
call writeint ; eax = -10
exit
main ENDP
END main

4. Stack Memory:
4.1. PUSH Instruction:
Syntax:
– PUSH register/variable16
– PUSH register/variable32
– PUSH Constant (any number)

4.2. POP Instruction:


Syntax:
– POP register/variable16
– POP register/variable32

Example of Stack:
CODE:
.data
var1 Dword 100
var2 Dword 200
var3 Dword 300
var4 Dword 400
var5 Dword ?

.code
main PROC
push var1
push var2
push var3
push var4
mov eax,500
push eax
pop eax
call writedec
call crlf
pop eax
call writedec
call crlf
pop eax
call writedec
call crlf
pop var5
mov eax,var5
call writedec
call crlf
pop eax
call writedec
call crlf
exit
main ENDP
END main

5. Random32:
The Random32 procedure generates and returns a 32-bit random integer in EAX.

Example:
.data
Value DWORD ?
.code
call Random32
mov Value,eax

6. RandomRange:
The RandomRange procedure produces a random integer within the range of 0 to n-1,
where n is an input parameter passed in the EAX register.

Example:
.data
Value DWORD ?
.code
mov eax,100
call RandomRange
mov Value,eax

7. Randomize:
Randomize generate a Unique sequence of numbers. You need only to call Randomize once
at the beginning of a program.

Example:
TITLE Randoms (main.asm)
INCLUDE Irvine32.inc
.data

.code
main PROC
call Randomize
mov ecx,10
L1:
mov eax,50
call RandomRange
call writeDec
call crlf
loop L1
exit
main ENDP
END main

8. ReadChar & WriteChar:


Example:
TITLE Readchar (main.asm)
INCLUDE Irvine32.inc

.data
char BYTE ?
.code
main proc
call ReadChar
mov char,al
call crlf
call writechar
exit
main ENDP
END main
9. ReadHex & WriteHex:
Example:
INCLUDE Irvine32.inc
.data
hex Dword ?
.code
main proc
call Readhex
mov hex,eax
call crlf
call writehex
exit
main ENDP
END main

10. INCREMENT (Inc):


Example:
.code
mov eax,10
call writedec
inc eax
call crlf
call writedec

11. DECREMENT (Dec):


Example:
.code
mov eax,10
call writedec
Dec eax
call crlf
call writedec

12. EXCHANGE (xchg):


Example:
.data
val DWORD 5
val2 DWORD 6
.code
main proc
mov eax,val
xchg eax,val2
call writeDec
call crlf
exit
main ENDP
END main

13. movzx Instruction:


Example for unsign word:
.data
value word 75
.code
main PROC
movzx eax,value
call writeint
call crlf
exit
main ENDP
END main

14. movsx Instruction:


Example for sign word:
.data
value Sword -75
.code
main PROC
movsx eax,value
call writeint
call crlf
exit
main END

Lab 7- Exercise:
LAB 8
Assembly Language Procedures

1. Assembly Procedures:
Procedures or subroutines are very important in assembly language, as the assembly
language programs tend to be large. Procedures are identified by a name. Following this
name, the body of the procedure is described which performs a well-defined job. End of the
procedure is indicated by a return statement.

Syntax:

Proc_name:
Procedure body
….
Ret

The procedure is called from another function by using the CALL instruction. The CALL
instruction should have the name of the called procedure as an argument as shown below:

Syntax:

Call Procedure_name

The called procedure returns the control to the calling procedure by using the RET
instruction.

CALL-RET Example (1 of 2)

main PROC
00000020 call MySub
0000025 is the offset of the instruction 00000025 mov eax,ebx
immediately following the CALL .
instruction .
main ENDP
MySub PROC
00000040 is the offset of the first 00000040 mov
instruction inside MySub eax,edx
.
.
ret
MySub ENDP
00000025 ESP 00000040
00000025 ESP 00000025
EIP
EIP

Example:
INCLUDE Irvine32.inc
.data
.code
addition PROC
add eax,ebx
ret
addition ENDP
main PROC
mov eax,4
mov ebx,3
call addition
call writedec
call crlf
exit
main ENDP
END main
2. Nested Procedure Call:

Example:
Remember the nested loop we created. It's easy to push the outer loop counter before
entering the inner loop:

CODE:
mov ecx,100 ; set outer loop count
L1: ; begin the outer loop
push ecx ; save outer loop count
mov ecx,20 ; set inner loop count
L2: ; begin the inner loop
;
loop L2 ; repeat the inner loop
pop ecx ; restore outer loop count
loop L1 ; repeat the outer loop

Lab 8- Exercise:
LAB 9
Assembly Floating Point Unit Stack

1. FPU Register Stack


The FPU does not use the general-purpose registers (EAX, EBX, etc.). Instead, it has its own
set of registers called a register stack. It loads values from memory into the register stack,
performs calculations, and stores stack values into memory.

2. Load Floating Point Instruction (FLD):


The FLD (load floating point value) instruction copies a floating point operand to the top of
the FPU stack [known as ST(0)]. The operand can be a 32-bit, 64-bit, or 80-bit memory
operand (REAL4, REAL8, REAL10) or another FPU register:
Syntax:
– FLD m32fp
– FLD m64fp
– FLD m80fp

Example: The following example loads two direct operands on the FPU
stack:
CODE:
.data
dblOne REAL8 23.4
dblTwo REAL8 10.1
.code
fld dblOne ; ST(0) = 23.4
fld dblTwo ; ST(0) = 10.1 , ST(1) = 23.4
3. Reading and Writing Floating-Point Values
3.1. ReadFloat:
Reads a floating-point value from the keyboard and pushes it on the floating-point stack.
Use “Call Readfloat” procedure for user input.

3.2. WriteFloat:
Writes the floating-point value at ST(0) to the console window in exponential format.
ReadFloat accepts a wide variety of floating-point formats.

Example:
35
+35.
-3.5
.35
3.5E5
3.5E005
-3.5E+5
3.5E-4
+3.5E-4
Use “Call Writefloat” procedure for Display.

4. ShowFPUStack procedure
ShowFPUStack Another useful procedure,displays the FPU stack. Call it with no
parameters:
CODE:
call ShowFPUStack
5. fstp instruction
CODE:
fstp variable_name ; store ST(0) to variable

6. finit instruction
Initialize floating point register stack with 0.

CODE:
Finit

Example:
.data
val Real4 ?
val2 Real4 ?
ans Real4 ?
msg1 byte "Enter 1st value :",0
msg2 byte "Enter 2nd value :",0
msg3 byte "Your Sum is :",0
msg4 byte "Your Sub is :",0
msg5 byte "Your mul is :",0
msg6 byte "Your div is :",0
.code
main PROC
finit
mov edx,offset msg1
call writestring
call readfloat
fstp val
call crlf
mov edx,offset msg2
call writestring
call readfloat
fstp val2
fld val2
fadd val
call crlf
mov edx,offset msg3
call writestring
call writefloat
call crlf
fld val
fsub val2
mov edx,offset msg4
call writestring
call writefloat
finit
fld val
fdiv val2
call crlf
mov edx,offset msg6
call writestring
call writefloat
fld val
fmul val2
call crlf
mov edx,offset msg5
call writestring
call writefloat
call crlf
exit
main ENDP
END main

7. READING & WRITING STRING:


Example:
.data
input_string BYTE 500 DUP(0)
store_string_length DWORD ?

.code
main PROC
mov edx,OFFSET input_string ; point to the input_string
mov ecx,SIZEOF input_string ; store maximum length characters
call ReadString ; take input from user
mov store_string_length,eax ; number of characters
mov edx,OFFSET input_string
call writestring
call crlf
exit
main ENDP
END main

Lab 9- Exercise:
LAB 10
Conditional LOOP

1. LOOPZ and LOOPE Instruction:


It is Useful when scanning an array for the first element that does not match a given value.

Syntax:
LOOPE destination
LOOPZ destination

Logic:
• ECX ← ECX – 1
• if ECX > 0 and ZF=1, jump to destination

2. LOOPNZ and LOOPNE Instruction:


It is Useful when scanning an array for the first element that matches a given value.

Syntax:
LOOPNZ destination
LOOPNE destination

Logic:
• ECX ← ECX – 1
• if ECX > 0 and ZF=0, jump to destination

Example LOOPNZ:
The following code finds the first positive value in an array:
CODE:
.data
array SWORD -3,-6,-1,-10,10,30,40,4
sentinel SWORD 0
.code
mov esi,OFFSET array
mov ecx,LENGTHOF array
next:
test WORD PTR [esi],8000h ; test sign bit
pushfd ; push flags on stack
add esi,TYPE array
popfd ; pop flags from stack
loopnz next ; continue loop
jnz quit ; none found
sub esi,TYPE array ; ESI points to value
quit:

NOTE: Locate the first nonzero value in the array. If none is found, let ESI point to the
sentinel value:

CODE:
.data
array SWORD 50 DUP(?)
sentinel SWORD 0FFFFh
.code
mov esi,OFFSET array
mov ecx,LENGTHOF array
L1: cmp WORD PTR [esi],0 ; check for zero

(fill in your code here)


.
.
.
quit:

Solution:
.data
array SWORD 50 DUP(?)
sentinel SWORD 0FFFFh
.code mov esi,OFFSET array
mov ecx,LENGTHOF array
L1: cmp WORD PTR [esi],0 ; check for zero
pushfd ; push flags on stack
add esi,TYPE array
popfd ; pop flags from stack
loope next ; continue loop
jz quit ; none found
sub esi,TYPE array ; ESI points to value
quit:

3. Block -Structured IF Statements:


Assembly language programmers can easily translate logical statements written in
C++/Java into assembly language. For example:
C++/Java CODE:
if( op1 == op2 )
X = 1;
else
X = 2;
Assembly CODE:
mov eax,op1
cmp eax,op2
jne L1
mov X,1
jmp L2
L1:
mov X,2
L2:

Task Example: Implement the following pseudo code in assembly


language. All values are unsigned:
CODE:
if( ebx <= ecx )
{
eax = 5;
edx = 6;
}

Implement the following pseudo code in assembly language. All values are 32-bit
signed integers:
if( var1 <= var2 )
var3 = 10;
else
{
var3 = 6;
var4 = 7;
}

4. Compound Expression with AND [1/3]:


When implementing the logical AND operator, consider that HLLs use short-circuit
evaluation.
In the following example, if the first expression is false, the second expression is skipped:

Expression:
if (al > bl) AND (bl > cl)

X = 1;
5. Compound Expression with AND [2/3]:
Expression:
if (al > bl) AND (bl > cl)
X = 1;

This is one possible implementation . . .


cmp al,bl ; first expression...
ja L1
jmp next
L1:
cmp bl,cl ; second expression...
ja L2
jmp next
L2: ; both are true
mov X,1 ; set X to 1
next:

6. Compound Expression with AND [3/3]:


Expression:
if (al > bl) AND (bl > cl)
X = 1;

But the following implementation uses 29% less code by reversing the
first relational operator.
cmp al,bl ; first expression...
jbe next ; quit if false
cmp bl,cl ; second expression...
jbe next ; quit if false
mov X,1 ; both are true
next:

Implement the following pseudo code in assembly language. All values


are unsigned:
if(ebx <= ecx) AND (ecx > edx )
{
eax = 5;
edx = 6;
}
7. Compound Expression with OR [1/2]:
When implementing the logical OR operator, consider that HLLs use short-circuit
evaluation.
In the following example, if the first expression is true, the second expression is skipped:

Expression:
if (al > bl) OR (bl > cl)
X = 1;

8. Compound Expression with OR [2/2]:


Expression:
if (al > bl) OR (bl > cl)
X = 1;

We can use "fall-through" logic to keep the code as short as possible:


cmp al,bl ; is AL > BL?
ja L1 ; yes
cmp bl,cl ; no: is BL > CL?
jbe next ; no: skip next statement
L1: mov X,1 ; set X to 1
next:

9. WHILE Loop:
A WHILE loop is really an IF statement followed by the body of the loop, followed by an
unconditional jump to the top of the loop. Consider the following example:

while( eax < ebx)


eax = eax + 1;

This is a possible implementation:


top:cmp eax,ebx ; check loop condition
jae next ; false? exit loop
inc eax ; body of loop
jmp top ; repeat the loop
next:
Task Example: Implement the following loop, using unsigned 32-bit
integers:
while( ebx <= val1)
{
ebx = ebx + 5;
val1 = val1 - 1 }

Lab 10- Exercise:


LAB 11
Integer Arithmetic and Bit Manipulation

1. Bitwise Logical Instructions:


The IA-32 instruction set contains the AND, OR, XOR, NOT, and TEST instructions that
implement bitwise logical operations. The source and destination operands can be bytes,
words, or double words, and they must be of the same size. These instructions are listed in
the table shown below:

2. Shift and Rotate Instructions:


Shifting is to move bits left and right inside an operand. There are two basic ways to shift
the bits. 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. The highest bit is
assigned 0 and the bit which is shifted out is stored in the carry flag.

The other type of shift is called an arithmetic shift. The newly created bit position is filled
with a copy of the original number’s sign bit. It works only with shift arithmetic right.
A drawback of the shift instructions is that the bits that are shifted out are lost, except that
the last bit shifted out is stored in the carry flag. There may be situations where we want to
keep these bits. The rotate instructions can be used instead. They are divided into two
types: the normal rotate, and the rotate through the carry flag. An example of a rotate
instruction is ROL (rotate left). This instruction shifts each bit to the left according to a
specific count. The highest bit rotates left to become the lowest bit. The last highest bit that
was rotated left is stored in the carry flag.

3. SHLD and SHRD Instructions:


The SHLD and SHRD are double precision shift instructions that operate on three operands.
The destination and source operands can be 16 or 32 bits, and they must be of the same
size. The count can be an 8-bit constant or the CL registers.
4. Binary Multiplication and Division:
Shift operations are very effective in multiplying or dividing binary numbers by a power of
2. In the binary number system, if we want to multiply a number by 2, we simply append a
0 to the right, which is analogous to shifting left by 1 bit. In general, shifting an integer n
bits to the left multiplies it by 2n . Similarly, division by 2 is analogous to shifting right by 1
bit. In general, shifting an integer n bits to the right divides it by 2n . This division process
corresponds to integer division, which discards any fractional part of the result. For signed
integers, we use shift arithmetic right instead of shift right to preserve the sign of the
integer. The following are examples:

5. Converting a Number to ASCII Hexadecimal Format:


The following procedure converts a 32-bit number stored in the EAX register into ASCII
hexadecimal format. It stores the hexadecimal characters in a string passed by reference.
The address of the string is passed as a parameter in the EDX register. A loop is used to
traverse all the bits of the EAX register. At the beginning of the loop iteration, the upper 4
bits of EAX are rotated left to become the lowest 4 bits. The ROL instruction is used for this
purpose. Then, the AND instruction keeps only the lower 4 bits in EBX by clearing all the
remaining bits. These 4 bits are used to index hexarray, which converts them into a
hexadecimal character. After repeating the loop 8 iterations, all the bits of EAX are
traversed and converted. Because the ROL instruction is used in loop L1, the value of the
EAX register is brought back to its initial value at the end of the loop.
CODE:
6. Convert2Bin procedure:

7. Integer Multiplication and Division:


The Intel instruction set lets you multiply and divide 8-bit, 16-bit, and 32-bit integers using
the MUL, IMUL, DIV, and IDIV instructions.

8. MUL and IMUL Instructions:


The MUL (unsigned multiply) instruction multiplies an 8-bit, 16-bit, or 32-bit operand by
AL, AX, or EAX. This instruction takes only one operand, which is the multiplier. The
multiplicand defaults to the AL, AX, or EAX register. It has the following format:
9. DIV and IDIV Instructions:
10. CBW, CWD, and CDQ Instructions:
Before doing signed integer division, the sign of a register must be extended into another register. The
CBW (Convert Byte to Word) instruction extends the sign bit of AL into the AH register. The CWD
(Convert Word to Double-word) instruction extends the sign bit of AX into the DX register. The CDQ
(Convert Double-word to Quad-word) instruction extends the sign bit of EAX into the EDX register.

11. Divide Overflow:


If a division operand produces a quotient that is too large to fit in the destination register, a
divide overflow condition results. This cause a CPU interrupts, and the current program
halts. For example, the following instructions generate a divide overflow because the
quotient (500h) cannot fit in the AL register.

12. Converting an Unsigned Integer to ASCII Decimal


Format:
To convert an unsigned integer to ASCII decimal format, we should divide it by 10 and find
the remainder. The remainder will be a number between 0 and 9. It represents the least
significant digit. We convert the digit to ASCII format by adding the character ‘0’. We repeat
the DIV instruction until the quotient becomes zero. We collect the digits one by one and
store them in a string. Since the least significant digit is computed first and the most
significant digit is computed last, we push them on the stack to avoid storing them in the
string in reverse order. A second loop is used to pop the digit characters off the stack and
store them in the string, as shown in the following Convert2Dec procedure:
13. Extended Addition and Subtraction:
The ADC (add with carry) instruction adds both a source operand and the content of the
carry flag to a destination operand. The SBB (subtract with borrow) instruction subtracts
both a source operand and the value of the carry flag from a destination operand. All the
arithmetic flags are affected by both instructions.
LAB 12
Stack Memory & It’s Parameters & Advance Procedures

1. Stack Parameters:
There are two basic ways of passing parameters to procedures. We can pass parameters in
registers or we can pass them on the stack. So far, we have demonstrated the use of register
parameters in the previous lab. The Irvine library also uses register parameters for its
procedures. Register parameters are optimized for program execution speed.
Stack parameters are pushed on the stack before making the procedure call. The called
procedure will have to locate its parameters on the stack.
Consider the SumOf procedure defined in the previous lab. We now redefine it and call it
differently, passing parameters on the stack, rather than in registers as shown below:
CODE Example:

When the SumOf procedure is called, the esp register is pointing at the return address on
top of the stack. The parameters can be located on the stack at addresses [esp+4], [esp+8],
and [esp+12]. Recall that the stack grows downwards towards lower addresses.
1. Cleaning up the Stack Parameters with the RET
Instruction:
When parameters are pushed on the stack, it is important to clean up the stack upon
returning from a procedure. The ret instruction can specify an extra integer constant to
clean up the parameters on the stack. In the above SumOf procedure, 12 bytes are pushed
on the stack for three parameters. The ret 12 instruction is used to increment the esp
register by 12 bytes, in addition to the 4 bytes for popping the return address.

2. Saving and Restoring Registers:


A procedure might need to use some general-purpose registers to carry its computation. To
preserve the values of these registers across a procedure call, it is important to push their
values at the beginning of the procedure and pop them at the end, so that the caller
program can be sure that none of its own register values are overwritten.

3. The EBP Register:


The esp register can be used in simple procedures, like the above SumOf, to access
parameters on the stack. However, in complex procedures, the esp register might change.
The ebp register can be used instead as a base register for accessing parameters on the
stack.

Example: Summing of integer Array:


The following procedure computes the sum of an array of integers. The first two
instructions save the old value of ebp and assign the value of esp to ebp. These two
instructions are commonly used in procedures that have their parameters on the stack. The
ebp register is used to access the parameters. The first parameter is located at address [ebp
+ 8] and the second parameter is at address [ebp + 12]. This is because 8 bytes are
allocated on the stack for the return address and the ebp register.
The ArraySum procedure uses the esi register to address the integer array and the ecx
register to count the number of elements. Since these two registers are modified by
ArraySum, their values have to be preserved. This is why, the esi and ecx registers are
pushed at the beginning and popped at the end, but in reverse order.
CODE:

The ArraySum procedure also uses the eax register to accumulate the sum and to hold the
result of the procedure. Since the result is returned in the eax register, its value should not
be preserved by the procedure.

4. Passing Parameters by Value and by Reference:


The ArraySum procedure receives two parameters on the stack. The first parameter is the
array address and the second parameter is the count of the number of elements. Rather
than passing the entire array on the stack, the address is passed only. This is called pass by
reference because the procedure uses the array address to access the array elements. It is
also possible to use the array address to modify the array elements. For example, a
procedure that reads an array of integers can use the array address to store the read
values. On the other hand, the second parameter, which is the element count, is passed by
value on the stack.

5. Local Variables and Stack Frames:


Procedures use local variables to carry the computation. If only few simple local variables
are needed, then registers can be used. However, if registers are not enough, then local
variables are allocated on the stack when the procedure is called, and freed when the
procedure returns.

Example: Taking the Sum of the Digits in a String:


The SumDigits procedure inputs a string of digits and then computes and returns the sum
of the string digits. The input string is a local variable stored on the stack.
CODE:
6. Stack Frame:
The SumDigits procedure receives one parameter on the stack. This parameter is the
address of the sum variable. After saving the old ebp value on the stack and setting the
value of ebp register, the 3rd instruction sub esp, 20 allocates 20 bytes for the local string
variable on the stack. To allocate space for local variables on the stack, we simply decrease
the value of the esp register by the size of the variables in bytes. One sub instruction is
sufficient to allocate space for all the local variables on the stack. The pushad instruction
then saves all the generalpurpose registers on the stack to preserve their values. Since
many of these registers are used, it is convenient to save all of them at the beginning of the
procedure and restore all of them at the end. The area of the stack, which is allocated for a
procedure’s parameters, return address, saved registers, and local variables is called a
stack frame. It is created by the following steps:
✓ Caller pushes parameters on the stack.
✓ Procedure is called; the return address is pushed on the stack.
✓ Procedure saves old EBP value on the stack and sets new EBP equal to ESP.
✓ A value is subtracted from ESP to create space for the local variables.
✓ Some or all the general-purpose registers are saved on the stack

7. Returning the Result of a Procedure:


We have shown you two ways to return the result of a procedure. The first choice is to use
one (or more) register to hold the result. For example, we have used the eax register to
hold the result of the ArraySum procedure. The second choice is to use pass by reference to
store indirectly the result, as in the SumDigits procedure. The mov [ebx], eax instruction
saves the accumulated sum at the address which was passed as a parameter on the stack. A
final remark about the SumDigits procedure is that the prompt string is defined at the end
of the procedure. The prompt string characters are stored after the procedure code, but
they will never be executed because they appear after the ret instruction.
8. PROTO and PROC Directives:
The PROTO directive declares a prototype for an existing procedure. A prototype specifies
a procedure’s name and parameter list. It allows you to call a procedure before defining it.
MASM requires a prototype for each procedure called by an INVOKE statement. Consider
the SumDigits procedure, you can write a prototype for it as follows:

When you specify the parameters of a procedure, the assembler will automatically generate
the first two instructions: push epb and mov ebp, esp. So, there is no need to write them.
The assembler will also insert a leave instruction just before the ret instruction. The leave
instruction is equivalent to two instructions: move esp, ebp and pop ebp. So, there is no
need to write them either. The assembler will also replace the ret instruction with ret n,
where n is equal to the size of the parameters in bytes, so there is no need to specify n. You
can also refer to a parameter by name, rather than by its address inside the procedure (e.g.,
you can replace [ebp+8] by sumaddr). The assembler will replace the parameter name by
its address.

9. INVOKE Directive:
The INVOKE directive simplifies a procedure call by allowing you to pass parameters to a
procedure in a single statement. You can invoke SumDigits as follows:

10. LOCAL Directive:


The LOCAL directive allows you to declare one or more local variables inside a procedure.
It must be placed on the line immediately following the PROC directive, as follows:
The assembler will compute the total number of bytes occupied by the local variables and
will generate the add esp, – n instruction to allocate n bytes on the stack. You can refer to
local variables declared by the LOCAL directive by name rather than by address inside a
procedure. The assembler will substitute the name with its corresponding address.

11. USES Directive:


The USES directive lets you list the names of the all the registers that you want to preserve
within a procedure. This directive tells the assembler to generate push instructions to save
these registers at the beginning, and to generate pop instructions that restore these
registers at the end of the procedure. You can couple USES with the PROC directive as
follows:

Example: SumDigits2:
The SumDigits2.asm program is a modified version of SumDigits.asm that uses assembler
directives to simplify the writing of a procedure. Assemble and link SumDigits2.asm. Open
the SumDigits2.lst file and examine the instructions marked with * inserted by the
assembler at the beginning and end of the SumDigits procedure.
CODE:
Lab 12- Exercise:
LAB 13
Recursion in Assembly Language

1. Recursive Procedure:
A recursive procedure is one that calls itself. There are two kind of recursion: direct and
indirect. In direct recursion, the procedure calls itself and in indirect recursion, the first
procedure calls a second procedure, which in turn calls the first procedure.
Recursion could be observed in numerous mathematical algorithms. For example, consider
the case of calculating the factorial of a number. Factorial of a number is given by the
equation:

Equation:
Factorial (n) = n * Factorial ( n – 1 ) for n > 0

Example:
Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 5 x factorial of 4 and this can be a good example of
showing a recursive procedure. Every recursive algorithm must have an ending condition,
i.e., the recursive calling of the program should be stopped when a condition is fulfilled. In
the case of factorial algorithm, the end condition is reached when n is 0.

1.1. EBP Registers:


Register use in the stack frame %ESP - Stack Pointer. ... The "Top of the stack" is an
occupied location, not a free one, and is at the lowest memory address. %EBP - Base
Pointer. This 32-bit register is used to reference all the function parameters and local
variables in the current stack frame.

1.2. ESP Registers:


ESP register. The ESP register serves as an indirect memory operand pointing to the top of
the stack at any time. ... When a word value is pushed onto the stack,
the assembler decreases the ESP (Stack Pointer) register by 2. When a word value is
popped off the stack, the assembler increases the ESP register by 2.

Example:

The following program shows how factorial n is implemented in


assembly language. To keep the program simple, we will calculate
factorial 3.
CODE:
INCLUDE Irvine32.inc
.data
.code
main PROC
push 3 ; calc 3!
call Factorial ; calculate factorial (EAX)
call WriteDec ; display it
call Crlf
exit
main ENDP
;----------------------------------------------------------
Factorial PROC
; Calculates a factorial.
; Receives: [ebp+8] = n, the number to calculate
; Returns: eax = the factorial of n
;----------------------------------------------------------
push ebp
mov ebp,esp
mov eax,[ebp+8] ; get n
cmp eax,0 ; n > 0?
ja L1 ; yes: continue
mov eax,1 ; no: return 1 as the value of 0!
jmp L2 ; and return to the caller
L1: dec eax ; Factorial(n-1)
push eax
call Factorial
; Instructions from this point on execute when each
; recursive call returns.
ReturnFact:
mov ebx,[ebp+8] ; get n
mul ebx ; EDX:EAX = EAX * EBX
L2: pop ebp ; return EAX
ret 4 ; clean up stack
Factorial ENDP
exit
main ENDP
END main

Lab 13- Exercise:

You might also like