0% found this document useful (0 votes)
533 views69 pages

EE Lab Manuls Fast Nu

The document is a lab manual for a computer organization and architecture course. It provides instructions and guidelines for 14 experiments covering topics like assembly language, registers, memory, addressing modes, branching, bit manipulations, subroutines, stacks, pipelines, and multitasking. It includes a list of required software tools like NASM assembler and MIPS simulators. The first experiment introduces students to assembly language programming using NASM and debugging tools on a simple program to add and subtract numbers.

Uploaded by

Muhammad Saad
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)
533 views69 pages

EE Lab Manuls Fast Nu

The document is a lab manual for a computer organization and architecture course. It provides instructions and guidelines for 14 experiments covering topics like assembly language, registers, memory, addressing modes, branching, bit manipulations, subroutines, stacks, pipelines, and multitasking. It includes a list of required software tools like NASM assembler and MIPS simulators. The first experiment introduces students to assembly language programming using NASM and debugging tools on a simple program to add and subtract numbers.

Uploaded by

Muhammad Saad
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/ 69

EL215-COMPUTER ORGANIZATION

AND ARCHITECTURE
LAB MANUAL

DEPARTMENT OF ELECTRICAL ENGINEERING,


FAST-NU, LAHORE
Lab Manual of Computer Organization and Architecture

Created by: ToobaJaved&Hina Tariq

Date: August 2015

Last Updated by: Shazia Ahmed

Date: August 2019

Approved by the HoD:

Date:

Page | 2
Lab Manual of Computer Organization and Architecture

Table of Contents
Sr. No. Description Page No.

1 List of Equipment 4

2 Experiment No.1, Introduction to the Assembler 5

3 Experiment No.2, Registers and Flags 9

4 Experiment No.3, Memory Model 12

5 Experiment No.4, Simulating Cache using MIPS Simulator 16

6 Experiment No.5, Addressing Modes 19

7 Experiment No.6, Memory Addressing 27

8 Experiment No.7, Branching 29

9 Experiment No.8, Bit Manipulations 32

10 Experiment No.9, Subroutines and Stack 36

11 Experiment No.10, Execution Time 40

12 Experiment No.11, Using BIOS Services and DOS functions 44

13 Experiment No.12 Instruction Pipeline 48

14 Experiment No.13, String Instructions 53

15 Experiment No.14, Multitasking 60

16 Appendix A:Lab Evaluation Criteria 63

17 Appendix B:Safety around Electricity 64

18 Appendix C: Guidelines on Preparing Lab Reports 66

Page | 3
Lab Manual of Computer Organization and Architecture

List of Equipment
Software Tools

Sr. No. Description

1 Netwide Assembler NASM

2 Advanced Fullscreen Debugger (AFD)

3 MIPS ICT (MIPS Cache simulator)

4 WINMIPS64 (MIPS program pipe-line simulator)

Page | 4
Lab Manual of Computer Organization and Architecture

EXPERIMENT-1
INTRODUCTION TO THE ASSEMBLER
OBJECTIVES

 How to write a simple assembly language program for x86 (x88) real mode.
 How to use the Assembler for editing, assembling and debugging an assembly
language program.
 How to use the debugger interface for understanding the computer organization.

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Introduction to the Netwide Assembler (NASM)


The Netwide Assembler, NASM, is an 80x86 assembler designed for portability and
modularity. It supports a range of object file formats, including Linux and NetBSD/FreeBSD
a.out, ELF, COFF, Microsoft 16-bit OBJ and Win32. It will also output plain binary files. Its
syntax is designed to be simple and easy to understand, similar to Intel's but less complex. It
supports Pentium, P6, MMX, 3DNow, SSE and SSE2 opcodes, and has macro capability. [1]
NASM Command-Line Syntax
To assemble a file, you issue a command of the form:

nasm [infile] [-o outfile] [-l listfile]

For example,

nasm test.asm –o test.com –l test.lst

will assemble test.asm into a .com file test.com and will produce a list file test.lst. By giving
the following command help on the nasm features is available: nasm –h With -hf, this will
also list the available output file formats, and what they are.

The -o Option: Specifying the Output File Name

NASM will normally choose the name of your output file for you; precisely how it does this is
dependent on the object file format. For Microsoft object file formats (obj and win32), it will
remove the .asm extension from your source file name and substitute .obj. For the binary
format it will simply remove the extension, so that myfile.asm produces the output file myfile.
If the output file already exists, NASM will overwrite it, unless it has the same name as the
input file, in which case it will give a warning and use nasm.out as the output file name

Page | 5
Lab Manual of Computer Organization and Architecture

instead. For situations in which this behavior is unacceptable, NASM provides the -o
command-line option, which allows you to specify your desired output file name. You invoke
-o by following it with the name you wish for the output file, either with or without an
intervening space. For example:
nasm -f bin program.asm -o program.com

nasm -f bin driver.asm –o driver.sys

Note that this is a small o, and is different from a capital O, which is used to specify
the number of optimization passes required.
The -f Option: Specifying the Output File Format
If you do not supply the -f option to NASM, it will choose an output file format for
you itself. In the distribution versions of NASM, the default is always bin.
Like -o, the intervening space between -f and the output file format is optional; so “-f
bin” and “-fbin” are both valid.
The -l Option: Generating a Listing File
If you supply the -l option to NASM, followed (with the usual optional space) by a file
name, NASM will generate a source-listing file for you, in which addresses and generated
code are listed on the left, and the actual source code, with expansions of multi-line macros on
the right. For example:

nasm -f elf myfile.asm -l myfile.lst

If a list file is selected, you may turn off listing for a section of your source with [list -
], and turn it back on with [list +], (the default).
The -X Option: Selecting an Error Reporting Format
This option can be used to select an error reporting format for any error messages that
might be produced by NASM.
Two error reporting formats may be selected. They are the -Xvc option and the -Xgnu
option. The GNU format is the default and looks like this:

filename.asm:65: error: specific error message

where filename.asm is the name of the source file in which the error was detected, 65 is the
source file line number on which the error was detected, “error” is the severity of the error
(this could be warning), and specific error message is a more detailed text message which
should help pinpoint the exact problem.
The other format, specified by -Xvc is the style used by Microsoft Visual C++ and
some other programs. It looks like this:
filename.asm(65) : error: specific error message

Page | 6
Lab Manual of Computer Organization and Architecture

Where the only difference is that the line number is in parentheses instead of being
delimited by colons.
The -E Option: Send Errors to a File
In NASM the “–E” option, which takes a filename argument that causes errors to be
sent to the specified files rather than standard error. Therefore you can redirect the errors into
a file by typing:

nasm -E myfile.err -f obj myfile.asm

The -i Option: Include File Search Directories


When NASM sees the %include or incbin directive in a source file, it will search for
the given file not only in the current directory, but also in any directories specified on the
command line by the use of the -i option. Therefore you can include files from a macro
library, for example, by typing

nasm -ic:\macrolib\ -f obj myfile.asm

(As usual, a space between -i and the path name is allowed and optional).
NASM, in the interests of complete source-code portability, does not understand the
file naming conventions of the OS it is running on; the string you provide as an argument to
the -i option will be prepended exactly as written to the name of the include file. Therefore the
trailing backslash in the above example is necessary.
The -p Option: Pre-Include a File
NASM allows you to specify files to be pre-included into your source file, by the use
of the -p option. So running nasm myfile.asm -p myinc.inc is equivalent to running nasm
myfile.asm and placing the directive %include "myinc.inc" at the start of the file.
For consistency with the -I, -D and -U options, this option can also be specified as -P.

NASM Is Case-Sensitive
One simple difference is that NASM is case-sensitive. It makes a difference whether
you call your label foo, Foo or FOO. If you're assembling to DOS or OS/2 .OBJ files, you can
invoke the UPPERCASE directive to ensure that all symbols exported to other code modules
are forced to be upper case; but even then, within a single module,
NASM will distinguish between labels differing only in case.
(Extracted from [1], for more details please see [2])

First Assembly language program:


Let us now write a simple assembly language program for a com file which should add
two numbers and subtract a third number from the sum, as shown below:

Page | 7
Lab Manual of Computer Organization and Architecture

; A PROGRAM TO ADD TWO NUMBERS AND SUBTRACT A THIRD ONE FROM THE SUM
; USING REGISTERS

[ORG 0x0100]
MOV AX, 5 ; LOAD FIRST NUMBER IN AX
MOV BX, 12 ; LOAD SECOND NUMBER IN BX
ADD AX, BX ; ACCUMULATE SUM IN AX
MOV BX, 14 ; LOAD THIRD NUMBER IN BX
SUB AX, BX ; ACCUMULATE SUM IN AX
MOV AX, 0x4C00 ; TERMINATE PROGRAM
INT 0x21

Let us save this in a file named test.asm. Now we use NASM to assemble this program
using the command:
nasm test.asm –o test.com –l test.lst

Which generates two files, test.com and test.lst. Now we will use a debugger to
monitor the execution of this program. The debugger we are using is Advanced Fullscreen
Debugger (AFD). We will use the load command to load the com file, as shown in Figure 1.1.

CMD > l test.com

Figure 1. 1

As shown in the Figure 1.1, the interface of the debugger is easy to understand and use. Using
F1 we can step through the code and see the changes taking place in the register contents.
PROBLEMS
Modify this program to generate the sum of four numbers, using registers, and watch its
execution in the debugger. Also explore the various functions available in the debugger (the
debugger has built-in context sensitive help).

Page | 8
Lab Manual of Computer Organization and Architecture

Post Lab Exercise


Write a program to Add three numbers in Ax register and store the result in Bx register. Also
tell the purpose of INT 0X21 statement in our program.
REFERENCES
1 http://nasm.sourceforge.net/doc/html/nasmdoc1.html
2 http://nasm.sourceforge.net.

Page | 9
Lab Manual of Computer Organization and Architecture

EXPERIMENT-2
REGISTERS AND FLAGS
OBJECTIVES

 How to interpret the different types of registers available in the IAPX86 architecture.
 How to use the different types of registers and how to manipulate them in assembly
language.
 How to interpret the function of flags and to use them effectively.
 How to perform arithmetic operations with registers.
 How to use the debugger for viewing the available registers and their function.

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

The 8086 chip uses registers for performing operations. Following is a brief detail of their
functions:

General registers: There are four 16-bit general-purpose registers used primarily to contain
operands for arithmetic and logical operations.

Segment registers: These special-purpose registers permit systems software designers to


choose either a flat or segmented model of memory organization. These four registers
determine, at any given time, which segments of memory are currently addressable.

Status and instruction registers: These special-purpose registers are used to record and
alter certain aspects of the 8086 processor state.

Flags Register: FLAGS is a 16-bit register which should be interpreted as a collection of


single bit flags rather than as a unit. The flags may be considered in two major groups: the
status flags and the control flags.

Status Flags: The status flags of the FLAGS register allow the results of one instruction to
influence later instructions. The arithmetic instructions use OF, SF, ZF, AF, PF, and CF. The
SCAS (Scan String), CMPS (Compare String), and LOOP instructions use ZF to signal that
their operations are complete. There are instructions to set, clear, and complement CF before
execution of an arithmetic instruction.

Control Flags: The control flag DF of the EFLAGS register controls string instructions.
Setting DF causes string instructions to auto-decrement; that is, to process strings from high
addresses to low addresses. Clearing DF causes string instructions to auto-increment, or to

Page | 10
Lab Manual of Computer Organization and Architecture

process strings from low addresses to high addresses.

Instruction Pointer: The instruction pointer register (IP) contains the offset address, relative
to the start of the current code segment, of the next sequential instruction to be executed. The
instruction pointer is not directly visible to the programmer; it is controlled implicitly by
control-transfer instructions, interrupts, and exceptions.

Table 2.1 Control Flags

Table 2.2 Summary of Registers


Segment
Registers
CS Code Segment 16-bit number that points to the active code-segment
DS Data Segment 16-bit number that points to the active data-segment
SS Stack Segment 16-bit number that points to the active stack-segment
ES Extra Segment 16-bit number that points to the active extra-segment
Pointer
Registers
IP Instruction 16-bit number that points to the offset of the next instruction
Pointer
SP Stack Pointer 16-bit number that points to the offset that the stack is using
BP Base Pointer used to pass data to and from the stack
General-
Purpose
Registers
AX Accumulator mostly used for calculations and for input/output
Register
BX Base Register Only register that can be used as an index
CX Count register used for the loop instruction
Register
DX Data Register input/output and used for multiply and divide
Index
Registers
SI Source Index used by string operations as source
DI Destination used by string operations as destination
Index

Page | 11
Lab Manual of Computer Organization and Architecture

PROBLEMS
1. Write a program to calculate the square of 20 by using a loop that adds 20 to the
accumulator 20 times.

POST LAB EXERCISES

1. Give the value of the IP, zero flag, the carry flag, the sign flag, and the overflow flag
after each of the following instructions if AX is initialized with 0x1254 and BX is
initialized with 0x0FFF.
add ax, 0xEDAB
add ax, bx
addbx, 0xF001

2. Write instructions that perform the following operations.


a. Copy BL into CL
b. Copy DX into AX
c. Store 0x12 into AL
d. Store 0x1234 into AX
e. Store 0xFFFF into AX

REFERENCES
1. The Art Of Assembly Language Programming, http://webster.cs.ucr.edu/Page_win32/
2. Intel 80386 Reference Programmer's Manual, http://www.logix.cz/michal/doc/i386/
3. Assembly Language Programming Book by Belal Mohammad Hashmi, NUCES
FAST, Lahore, Pakistan
4. Assembly Tutorial, http://www.geocities.com/SiliconValley/6112/asm0100.htm

Page | 12
Lab Manual of Computer Organization and Architecture

EXPERIMENT-3
MEMORY SYSTEM
OBJECTIVES

 To be able to do 32 bit computations using 16 bit registers


 To learn the x86 memory system segmentation
SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Depending on the machine, a processor can access one or more bytes from memory at a time.
The number of bytes accessed simultaneously from main memory is called word length of
machine. Generally, all machines are byte-addressable i.e.; every byte stored in memory has a
unique address. However, word length of a machine is typically some integral multiple of a
byte. Therefore, the address of a word must be the address of one of its constituting bytes. In
this regard, one of the following methods of addressing (also known as byte ordering) may be
used.

Big Endian– the higher byte is stored at lower memory address (i.e. Big Byte first). MIPS,
Apple, Sun SPARC are some of the machines in this class .
Little Endian - the lower byte is stored at lower memory address (i.e. Little Byte first). Intel’s
machines use little endian.
Consider for example, storing 0xA2B1C3D4 in main memory. The two byte orderings are illustrated in
Figure 3.1

Figure 3. 1
Memory Models

In earlier processors like 8080 and 8085 the linear memory model was used to access memory.

Flat/ Linear Memory Model – memory appears to a program as a single, contiguous address
space of 4GB. Code, data, and stack are all contained in this address space, also called the
linear address space

Page | 13
Lab Manual of Computer Organization and Architecture

8080 and 8085 could access a total memory of 64K using the 16 lines of their address bus.
When designing iAPX88 the Intel designers wanted to remain compatible with 8080 and 8085
however 64K was too small to continue with, for their new processor. The three logical parts
of a program (data, code and stack) should appear as three distinct units in memory, but
making this division is not possible in the linear memory model. The segmented memory
model does allow this distinction.

Segmented Memory Model – memory appears to a program as a group of independent


memory segments, where code, data, and program stack are contained in separate memory
segments. To address memory in this model, the processor must use segment registers and an
offset to derive the linear address. The primary reason for having segmented memory is to
increase the system's reliability by means of protecting one segment from other.

The processor sees code from the code window and data from the data window. The size of
one window is restricted to 64K. 8085 software fits in just one such window. It sees code,
data, and stack from this one window, so downward compatibility is attained. However the
maximum memory iAPX88 can access is 1MB which can be accessed with 20 bits. Compare
this with the 64K of 8085 that were accessed using 16 bits. The idea is that the 64K window
just discussed can be moved anywhere in the whole 1MB. The four segment registers
discussed in the Intel register architecture are used for this purpose. Therefore four windows
can exist at one time. For example one window that is pointed to by the CS register contains
the currently executing code.

Segment Registers
The segment registers hold the segment selectors which are special pointers that point to start
of individual segments in memory. The use of segment registers is dependent on the memory
management model in use. When using the segmented memory model, each segment is loaded with
a different memory address as shown in the Figure 3.1

Figure 3. 2

Page | 14
Lab Manual of Computer Organization and Architecture

The segment registers (CS, DS, SS, ES, FS, and GS) hold 16-bit segment selectors. To access
a particular segment in memory, the segment selector for that segment must be present in the
appropriate segment register. Each of the segment registers is associated with one of three
types of storage: code, data, or stack. The DS, ES, FS, and GS registers point to four data
segments. The availability of four data segments permits efficient and secure access to
different types of data structures.
The CS register contains the segment selector for the code segment, where the
instructions being executed are stored. The processor fetches instructions from the code
segment, using a logical address that consists of the segment selector in the CS register and the
contents of the IP (Instruction Pointer) register. The CS register opens a 64K window in the
1MB memory and then IP works to select code from this window as offsets. IP is 16 bit wide
and works only inside this window and cannot go outside of this 64K in any case. If the
window is moved i.e. the CS register is changed, IP will change its behavior accordingly and
start selecting from the new window. The IP register always works relatively, relative to the
segment base stored in the CS register.

Physical Address Calculation


Now for the whole megabyte we need 20 bits while CS and IP are both 16bit registers. We
need a mechanism to make a 20bit number out of the two 16bit numbers. Consider that the
segment value is stored as a 20 bit number with the lower four bits zero and the offset value is
stored as another 20 bit number with the upper four bits zeroed. The two are added to produce
a 20bit absolute address. A carry if generated is dropped without being stored anywhere and
the phenomenon is called address wraparound. The process is explained with the help of the
Figure 3.3.

Figure 3. 3

Example:
The program we wrote when loaded into memory had a value of 0100 in IP register and some
value say 1DDD in the CS register. Making both 20 bit numbers, the segment base is 1DDD0
and the offset is 00100 and adding them we get the physical memory address of 1DED0 where
the opcode B80500 is placed.

Page | 15
Lab Manual of Computer Organization and Architecture

Problems:

1. Fill in the tables (table 3.1 and table 3.2) to show storage of 0xABDADDBA at address
1996 in the memory of a machine using (i) little endian (ii) big
endian byte ordering.
table3. 1 table3. 2

Address Contents Address Contents


1996 1996
1997 1997
1998 1998
1999 1999
Little Endian Big Endian

2. Calculate the physical memory address generated by the following segment offset
pairs.
a) 1DDD:0436
b) 1234:7920
c) 74F0:2123
d) 0000:6727
e) FFFF:4336
3. Write instructions to do the following.
a. Copy contents of memory location with offset 0025 in the current data segment into
AX.
b. Copy AX into memory location with offset 0FFF in the current data segment.
c. Move contents of memory location with offset 0010 to memory location with offset
002F in the current data segment.

4. Write a program to implement 32-bit increment and decrement operations using


registers AX and BX. (Hint: Use SBB and ADC)
POST LAB Exercise
1) Extend the code in problem – 3, such that your code adds two 32 bit numbers

Page | 16
Lab Manual of Computer Organization and Architecture

EXPERIMENT-4
SIMULATING CACHE USING MIPS SIMULATOR
OBJECTIVES

 To be able to understand working of cache


 To learn the use of MIPS simulator

SOFTWARE TOOLS:

 MIPS ICT (MIPS Cache simulator)

THEORY

 Refer to Chapter – 4 in order to understand cache principles


 Refer to the given document “Getting Started with MIPS Simulator” to understand
how to use MIPS simulator.

EXPERIMENT

 Create a new project in MipsIt using the steps mentioned in the given document.
 Compile code1.c and load it to the simulator
 Open the simulator and disable both cache
 Run the simulation and note down the execution time in Table 4.1
 Now enable the instruction cache only with default settings. Reload the code and
simulate it. Note down the execution time in table 4.1.
 Next, enable the data cache only and note down the time
 Now enable both cache (data+ instruction) and note down the time

Table 4.1
Instruction Data cache Both caches
Scenario No Cache
Cache only only
Time

 Which scenario took the least time? What is the reason?

 Enable both cache with default values. Play the simulation. Open the Instruction Cache
block by double clicking on it. What type of mapping is used by this cache? Looking at
the default values, calculate the word offset bits, cache line bits and tag bits and verify
it with simulator block diagram.

 Complete the table 4.2 for the same scenario

Page | 17
Lab Manual of Computer Organization and Architecture

Table 4.2
INSTRUCTION CACHE DATA CACHE
Hit Count Hit Count

Miss Count Miss Count

Hit Rate Hit Rate

Cycle Count Cycle Count

 Set the following values given in Table 4.3 in the simulator

Table 4.3

 Set Memory write buffer size = 5

 What is the type of cache Mapping?

 Reload the code, open the cache and memory windows, then press play. During
simulation, verify by noting down the observations of Data Cache and Memory
Locations that with “Write through” method, every time the processor writes to a
cached memory location both the cache and the underlying memory locations are
updated.

 How much is the Total time taken?

 Now change the data cache write policy to “Write back”. What are the changes you see
in the cache block?

 After the changes in 16, note the total time again.

Page | 18
Lab Manual of Computer Organization and Architecture

 Verify by noting down the observations of Data Cache and Memory Locations that
with “Write Back” method, when a write is made to system memory at a location that
is currently cached, the new data is only written to the cache, not actually written to the
system memory. Later, if another memory location needs to use the cache line where
this data is stored, it is saved ("written back") to the system memory and then the line
can be used by the new address.

 Considering the total execution time, comment which write policy is better?

POST LAB Exercise:

Write in detail the types of caches, their use and different functionalities.

Page | 19
Lab Manual of Computer Organization and Architecture

EXPERIMENT-5
ADDRESSING MODES
OBJECTIVES
 How to modify the memory contents.
 How to use various addressing modes.
 How to use the registers associated with memory.
 How to use segmentation.
 How use instructions like CALL, RET, PUSH and POP etc. with reference to the
stack.

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY
Stack Implementation:
Stack operations are facilitated by three registers:
1. The stack segment (SS) register. Stacks are implemented in memory. A system may
have a number of stacks that is limited only by the maximum number of segments. A
stack may be up to 4 gigabytes long, the maximum length of a segment. One stack is
directly addressable at the address located by SS. This is the current stack, often
referred to simply as "the" stack. SS is used automatically by the processor for all stack
operations.
2. The stack pointer (SP) registers points to the top of the push-down stack. It is
referenced implicitly by PUSH and POP operations, subroutine calls and returns, and
interrupt operations. When an item is pushed onto the stack, the processor decrements
SP, then writes the item at the new position. When an item is popped off the stack, the
processor copies it from the top position, then increments ESP. In other words, the
stack grows down in memory toward lesser addresses.
3. The stack-frame base pointer (BP) register is the best choice of register for accessing
data structures, variables and dynamically allocated work space within the stack. BP is
often used to access elements on the stack relative to a fixed point on the stack rather
than relative to the current top of stack. It typically identifies the base address of the
current stack frame established for the current procedure. When BP is used as the base
register in an offset calculation, the offset is calculated automatically in the current
stack segment (i.e., the segment currently selected by SS). Because SS does not have
to be explicitly specified, instruction encoding in such cases is more efficient. BP can
also be used to index into segments addressable via other segment registers. [2 and 3]

Page | 20
Lab Manual of Computer Organization and Architecture

An example of the working of the stack is given in Figure 5.1:

Figure 5. 1

Addressing Modes
The x86 processors support the register addressing mode, the immediate addressing
mode, the indirect addressing mode, the indexed addressing mode, and the direct addressing
mode. The following paragraphs explain each of these modes:
Register Addressing Mode: Register operands are the easiest to understand. Consider the
following forms of the MOV instruction:
MOV AX, AX
MOV AX, BX
MOV AX, CX
MOV AX, DX

The first instruction accomplishes absolutely nothing. It copies the value from the AX register
back into the AX register. The remaining three instructions copy the value of BX, CX and DX
into AX. Note that the original values of BX, CX, and DX remain the same. The first operand
(the destination) is not limited to AX; you can move values to any of these registers.

Immediate Addressing Mode: Constants are also pretty easy to deal with. Consider the
following instructions:
MOV AX, 25H
MOV BX, 195H
MOV CX, 2056H
MOV DX, 1000H

These instructions are all pretty straightforward; they load their respective registers with the
specified hexadecimal constant.

Direct Addressing Mode: There are three addressing modes which deal with accessing data in
memory. These addressing modes take the following forms:
MOV AX, [1000]

Page | 21
Lab Manual of Computer Organization and Architecture

The first instruction above uses the direct addressing mode to load AX with the 16 bit value
stored in memory starting at location 1000 hex.
Indirect Addressing Mode:
MOV AX, [BX]
MOV AX, [1000+BX]
The MOV AX, [BX] instruction loads AX from the memory location specified by the contents
of the BX register. This is an indirect addressing mode. Rather than using the value in BX,
this instruction accesses to the memory location whose address appears in BX. Note that the
following two instructions:
MOV BX, 1000
MOV AX, [BX]
are equivalent to the single instruction:

MOV AX, [1000]


Of course, the second sequence is preferable. However, there are many cases where the use of
indirection is faster, shorter, and better.

Indexed Addressing Mode: The last memory addressing mode is the indexed addressing
mode. An example of this memory addressing mode is

MOV AX, [1000+BX]


This instruction adds the contents of BX with 1000 to produce the address of the memory
value to fetch. This instruction is useful for accessing elements of arrays, records, and other
data structures.

The CALL and RET Instructions


The call and ret instructions handle subroutine calls and returns. There are five different call
instructions and six different forms of the return instruction:

CALL DISP16 ;directintrasegment, 16 bit relative.


CALL ADRS32 ;direct intersegment, 32 bit segmented address.
CALL MEM16 ;indirectintrasegment, 16 bit memory pointer.
CALL REG16 ;indirectintrasegment, 16 bit register pointer.
CALL MEM32 ;indirect intersegment, 32 bit memory pointer.
RET ;near or far return
RETN ;near return
RETF ;far return
RET DISP ;near or far return and pop
RETN DISP ;near return and pop
RETF DISP ;far return and pop

The call instructions take the same forms as the jmp instructions except there is no short (two
byte) intra-segment call.

Page | 22
Lab Manual of Computer Organization and Architecture

The far call instruction does the following:

 It pushes the CS register onto the stack.


 It pushes the 16 bit offset of the next instruction following the call onto the stack.
 It copies the 32 bit effective address into the CS:IP registers. Since the call instruction
allows the same addressing modes as jmp, call can obtain the target address using a
relative, memory, or register addressing mode.
 Execution continues at the first instruction of the subroutine. This first instruction is
the opcode at the target address computed in the previous step.
 The near call instruction does the following:
 It pushes the 16 bit offset of the next instruction following the call onto the stack.
 It copies the 16 bit effective address into the ip register. Since the call instruction
allows the same addressing modes as jmp, call can obtain the target address using a
relative, memory, or register addressing mode.
 Execution continues at the first instruction of the subroutine. This first instruction is
the opcode at the target address computed in the previous step.

The call disp16 instruction uses relative addressing. You can compute the effective address of
the target by adding this 16 bit displacement with the return address (like the relative jmp
instructions, the displacement is the distance from the instruction following the call to the
target address).

The call adrs32 instruction uses the direct addressing mode. A 32 bit segmented address
immediately follows the call opcode. This form of the call instruction copies that value
directly into the CS:IPregister pair. In many respects, this is equivalent to the immediate
addressing mode since the value this instruction copies into the CS:IPregister pair
immediately follows the instruction.

Call mem16 uses the memory indirect addressing mode. Like the jmp instruction, this form of
the call instruction fetches the word at the specified memory location and uses that word's
value as the target address.

Call reg16 works just like the memory indirect call above, except it uses the 16 bit value in a
register for the target address. This instruction is really the same instruction as the call mem16
instruction. Both forms specify their effective address using a modreg- r/m byte. For the call
reg16 form, the mod bits contain 11b so the r/m field specifies a register rather than a memory
addressing mode. Of course, this instruction also pushes the 16 bit offset of the next
instruction onto the stack as the return address.

The call mem32 instruction is a far indirect call. The memory address specified by this
instruction must be a double word value. This form of the call instruction fetches the 32 bit
segmented address at the computed effective address and copies this double word value into
the cs:ip register pair. This instruction also copies the 32 bit segmented address of the next

Page | 23
Lab Manual of Computer Organization and Architecture

instruction onto the stack (it pushes the segment value first and the offset portion second).
Like the call mem16 instruction, you can use any valid memory addressing mode with this
instruction:
It is relatively easy to synthesize the call instruction using two or three other 80x86
instructions. You could create the equivalent of a near call using a push and a jmp instruction:

Push <offset of instruction after jmp>


jmp subroutine

A far call would be similar, you'd need to add a push CS instruction before the two
instructions above to push a far return address on the stack.

The ret (return) instruction returns control to the caller of a subroutine. It does so by popping
the return address off the stack and transferring control to the instruction at this return address.
Intrasegment (near) returns pop a 16 bit return address off the stack into the ip register. An
intersegment (far) return pops a 16 bit offset into the ip register and then a 16 bit segment
value into the cs register. These instructions are effectively equal to the following:

retn: pop ip
retf: popdcs:ip

Clearly, you must match a near subroutine call with a near return and a far subroutine call with
a corresponding far return. If you mix near calls with far returns or vice versa, you will leave
the stack in an inconsistent state and you probably will not return to the proper instruction
after the call. Of course, another important issue when using the CALL and RET instructions
is that you must make sure your subroutine doesn't push something onto the stack and then fail
to pop it off before trying to return to the caller. Stack problems are a major cause of errors in
assembly language subroutines. [2]

The PUSH and POP Instructions


The 80x86 push and pop instructions manipulate data on the 80x86's hardware stack.
Following are the varieties of the push and pop instructions:

PUSH REG16
POP REG16
PUSH SEGREG
POP SEGREG (EXCEPT CS)
PUSH MEMORY
POP MEMORY
PUSHF
POPF

Page | 24
Lab Manual of Computer Organization and Architecture

The first two instructions push and pop a 16 bit general purpose register. This is a compact
(one byte) version designed specifically for registers.
The third pair of push/pop instructions let you push or pop an 80x86 segment register. Note
that the instructions that push FS and GS are longer than those that push CS, DS, ES, and SS.
You can only push the CS register (popping the CS register would create some interesting
program flow control problems).

The fourth pair of push/pop instructions allow you to push or pop the contents of a memory
location. On the 80286 and earlier, this must be a 16 bit value.

The pushf and popf instructions allow you to push/pop the processor status register (the flags).

Following is an algorithmic description of each instruction:

push instructions (16 bits):


SP := SP - 2
[SS:SP] := 16 bit operand (store result at location SS:SP.)

pop instructions (16 bits):


16-bit operand := [SS:SP]
SP := SP + 2

Notice three things about the 80x86 hardware stack. First, it is always in the stack segment
(wherever SS points). Second, the stack grows down in memory. That is, as you push values
onto the stack the CPU stores them into successively lower memory locations. Finally, the
80x86 hardware stack pointer (SS:SP) always contains the address of the value on the top of
the stack (the last value pushed on the stack).

You can use the 80x86 hardware stack for temporarily saving registers and variables, passing
parameters to a procedure, allocating storage for local variables, and other uses. The push and
pop instructions are extremely valuable for manipulating these items on the stack.
(Extracted from [1], [2] and [4])

Problems:
1. Write an assembly language program, which selects the smallest, largest, and equal
number among the three 4 byte numbers stored in variables. And store these smallest,
largest, and equal numbers at some memory place. Use values given in Figure 5.2 but at
evaluation time values can be changed
Note: Do not use extended registers, if you want to use extended registers then use 8 byte
numbers for the above process. (This is not the input from the keyboard and output to the
console.)

Page | 25
Lab Manual of Computer Organization and Architecture

Figure 5. 2

2. Implement the following C function into its corresponding assembly language.


Note: use PUSH, POP statements for parameter passing.

Void function (int x, int y, int&Avg, int& sum)


{
sum=x+y;
Avg= (x+y)/2;

}
3. Write the code to shift the whole stack at the offset of 0X20 from the current stack
location. Note: (You have to shift the data placed at the stack as well)

REFERENCES
1. Wikipedia, Free Online Encyclopedia,
http://en.wikipedia.org/wiki/X86#Real_mode
2. The Art Of Assembly Language Programming,
http://webster.cs.ucr.edu/Page_win32/
3. Intel 80386 Reference Programmer's Manual,
http://www.logix.cz/michal/doc/i386/
4. Assembly Language Programming Book by Belal Mohammad Hashmi, NUCES FAST,
Lahore, Pakistan

Page | 26
Lab Manual of Computer Organization and Architecture

EXPERIMENT-6
MEMORY ADDRESSING
OBJECTIVES
 How to modify the memory contents.
 How to use segmentation.

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Effective Address:

All the addressing mechanisms in iAPX88 return a number called effective address. For
example in base + offset addressing, neither the base nor the offset alone tells the desired cell
in memory to be accessed. It is only after the addition is done that the processor knows which
cell to be accessed. This number which came as the result of addition is called the effective
address. But the effective address is just an offset and is meaningless without a segment. Only
after the segment is known, we can form the physical address that is needed to access a
memory cell.

Example:
For example if BX=0100, SI=0200, and CS=1000 and the memory access under consideration
is [cs:bx+si+0x0700], the effective address formed is bx+si+0700 = 0100 + 0200 + 0700 =
0A00. Now multiplying the segment value by 16 makes it 10000 and adding the effective
address 00A00 forms the physical address 10A00 inside Code Segment (CS).

There are a few common mistakes done in forming a valid memory access. Part of a register
cannot be used to access memory. Like BX is allowed to hold an address but BL or BH are
not. Address is 16bit and must be contained in a 16 bit register. BX-SI is not possible. The
only thing that we
can do is addition of a base register with an index register. Any other operation is disallowed.
BX+BP and SI+DI are both disallowed as we cannot have two base or two index registers in
one memory access. One has to be a base register and the other has to be an index register and
that is the reason of naming them differently.

Problems:

1. What is the effective address generated by the following instructions? Every


instruction is independent of others. Initially BX=0x0100, num1=0x1001,
[num1]=0x0000, and SI=0x0100

Page | 27
Lab Manual of Computer Organization and Architecture

a) mov ax, [bx+12]


b) mov ax, [bx+num1]
c) mov ax, [num1+bx]
d) mov ax, [bx+si]

1. What is the effective address generated by the following combinations if they are
valid. If not, give reason. Initially BX=0x0100, SI=0x0010, DI=0x0001,
BP=0x0200, and SP=0xFFFF
a. bx-si
b. bx-bp
c. bx+10
d. bx-10
e. bx+sp
f. bx+di

2. Write an assembly language program, which changes the case of letters given in
the input string e.g given in Figure 6.1, string length and letter will be different at
evaluation time. And write the results in the output string. Input and Output strings
are to declare in the DATA segment.

Figure 6. 1

3. Write a program to add ten numbers using register + offset addressing mode.

Page | 28
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 7
BRANCHING
OBJECTIVES
 To understand various jump instructions
 To get familiarize with Relative Addressing
 To get an idea of types of jump instructions

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Please refer to the instruction set for various jump instructions.

RELATIVE ADDRESSING

Consider that, if inside the debugger, an instruction is shown as JMP 0119 and the location
0119 contains the original first instruction of the logic of our program. This jump is
unconditional, it will always be taken. Now looking at the opcode for this instruction, we see
EB1600 where EB is the opcode and 1600 is the operand to it. 1600 is 0016 in proper word
order. 0119 is not given as a parameter rather 0016 is given. This is position relative
addressing in contrast to absolute addressing. It is not telling the exact address rather it is
telling how much forward or backward to go from the current position of IP in the current
code segment. So the instruction means to add 0016 to the IP register. At the time of execution
of the first instruction at 0100 IP was pointing to the next instruction at 0103, so after adding
16 it became 0119, the desired target location. The mechanism is important to know, however
all calculations in this mechanism are done by the assembler and by the processor. We just use
a label with the JMP instruction and are ensured that the instruction at the target label will be
the one to be executed.

Types of JUMP:
The three types of jump, near, short, and far, differ in the size of instruction and the range of
memory they can jump to with the smallest short form of two bytes and a range of just 256
bytes to the far form of four bytes and a range covering the whole memory. Size of address for
all three types of jumps is given in Figure 7.1

Page | 29
Lab Manual of Computer Organization and Architecture

Figure 7. 1
Short Jump

If the offset is stored in a single byte as in 75F2 with the opcode 75 and operand F2, the jump
is called a short jump. F2 is added to IP as a signed byte. If the byte is negative the
complement is negated from IP otherwise the byte is added. Unconditional jumps can be short,
near, and far. Conditional jumps can only be short. A short jump can go +127 bytes ahead in
code and -128 bytes backwards and no more.
This is the limitation of a byte in singed representation.
Near Jump

When the relative address stored with the instruction is in 16 bits as in the last example the
jump is called a near jump. Using a near jump we can jump anywhere within a segment. If we
add a large number it will wrap around to the lower part. A negative number actually is a large
number and works this way using the wraparound behavior.
Far Jump

Far jump is not position relative but is absolute. Both segment and offset must be given to a
far jump. The previous two jumps were used to jump within a segment. Sometimes we may
need to go from one code segment to another, and near and short jumps cannot take us there.
Far jump must be used and a two byte segment and a two byte offset are given to it. It loads
CS with the segment part and IP with the offset part. Execution therefore resumes from that
location in physical memory. The three instructions that have a far form are JMP, CALL, and
RET, are related to program control. Far capability makes intra segment control possible.

Page | 30
Lab Manual of Computer Organization and Architecture

Exercise:
1. If AX=8FFF and BX=0FFF and “cmp ax, bx” is executed, which of the following
jumps will be taken? Each part is independent of others. Also give the value of Z, S,
and C flags.

a. jg greater
b. jl smaller
c. ja above
d. jb below

2. Write a program to search a particular element from an array using binary search. If
the element is found set AX to one and otherwise to zero.

3. Write a program to calculate the factorial of a number where factorial is defined as:

factorial(x) = x*(x-1)*(x-2)*...*1
factorial(0) = 1

Post Lab Exercise:

1) Write a program to Sort a particular 5 element array using selection sort.

Page | 31
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 8
BIT MANIPULATIONS

OBJECTIVES
 To be able to use shifting and rotation instructions
 To get familiarize with logical instructions

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Shifting and Rotations:

Shift Logical Right (SHR)


The shift logical right operation inserts a zero from the left and moves every bit one position
to the right and copies the rightmost bit in the carry flag as shown in Figure 8.1.

Figure 8. 1

Shift Logical Left (SHL) / Shift Arithmetic Left (SAL)


The shift logical left operation is the exact opposite of shift logical right. In this operation the
zero bit is inserted from the right and every bit moves one position to its left with the most
significant bit dropping into the carry flag as shown in Figure 8.2.

Figure 8. 2

Shift Arithmetic Right (SAR)


A signed number holds the sign in its most significant bit. If this bit was one a logical right
shifting will change the sign of this number because of insertion of a zero from the left. The
sign of a signed number should not change because of shifting. The operation of shift
arithmetic right is therefore to shift every bit one place to the right with a copy of the most
significant bit left at the most significant place as shown in Figure 8.3.

Page | 32
Lab Manual of Computer Organization and Architecture

Figure 8. 3

The left shifting operation is basically multiplication by 2 while the right shifting operation is
division by two. However for signed numbers division by two can be accomplished by using
shift arithmetic right and not shift logical right. The left shift operation is equivalent to
multiplication except when an important bit is dropped from the left. The overflow flag will
signal this condition if it occurs and can be checked with JO. For division by 2 of a signed
number logical right shifting will give a wrong answer for a negative number as the zero
inserted from the left will change its sign. To retain the sign flag and still effectively divide by
two the shift arithmetic right instruction must be used on signed numbers.

Rotate Right (ROR)


In the rotate right operation every bit moves one position to the right and the bit dropped from
the right is inserted at the left. This bit is also copied into the carry flag as shown in Figure 8.4.

Figure 8. 4

Rotate Left (ROL)


In the operation of rotate left instruction, the most significant bit is copied to the carry flag and
is inserted from the right, causing every bit to move one position to the left as shown in Figure
8.5. It is the reverse of the rotate right instruction.

Figure 8. 5

Rotate Through Carry Right (RCR)


In the rotate through carry right instruction, the carry flag is inserted from the left, every bit
moves one position to the right, and the right most bit is dropped in the carry flag as shown in
Figure 8.6. Effectively this is a nine bit or a seventeen bit rotation instead of the eight or
sixteen bit rotation as in the case of simple rotations.

Page | 33
Lab Manual of Computer Organization and Architecture

Figure 8. 6

Rotate Through Carry Left (RCL)


The exact opposite of rotate through carry right instruction is the rotate through carry left
instruction. In its operation the carry flag is inserted from the right causing every bit to move
one location to its left and the most significant bit occupying the carry flag as shown in Figure
8.7. The concept is illustrated below in the same manner as in the last example.

Figure 8. 7

 Bitwise Logical Operations:


The important thing about these operations is that they are bitwise. This means that if “and ax,
bx” instruction is given, then the operation of AND is applied on corresponding bits of AX
and BX. There are 16 AND operations as a result; one for every bit of AX. Bit 0 of AX will be
set if both its original value and Bit 0 of BX are set, bit 1 will be set if both its original value
and Bit 1 of BX are set, and so on for the remaining bits. These operations are conducted in
parallel on the sixteen bits. Similarly the operations of other logical operations are bitwise as
well.

Logical Operations include: AND, OR, XOR, NOT. Refer to the instruction set for the syntax.

 MASKING OPERATIONS

 Selective Bit Clearing

Another use of AND is to make selective bits zero in its destination operand. The source
operand is loaded with a mask containing one at positions which are retain their old value and
zero at positions which are to be zeroed. The effect of applying this operation on the
destination with mask in the source is to clear the desired bits. This operation is called
masking. For example if the lower nibble is to be cleared then the operation can be applied
with F0 in the source. The upper nibble will retain its old value and the lower nibble will be
cleared.

Page | 34
Lab Manual of Computer Organization and Architecture

 Selective Bit Setting

The operation can be used as a masking operation to set selective bits. The bits in the mask are
cleared at positions which are to retain their values, and are set at positions which are to be set.
For example to set the lower nibble of the destination operand, the operation should be applied
with a mask of 0F in the source. The upper nibble will retain its value and the lower nibble
will be set as a result.
 Selective Bit Inversion

XOR can also be used as a masking operation to invert selective bits. The bits in the mask are
cleared at positions, which are to retain their values, and are set at positions, which are to be
inverted. For example to invert the lower nibble of the destination operand, the operand should
be applied with a mask of 0F in the source. The upper nibble will retain its value and the lower
nibble will be set as a result. Compare this with NOT which inverts everything. XOR on the
other hand allows inverting selective bits.

Problems

1. Write a program to swap the nibbles in each byte of the AX register.

2. AX contains a non-zero number. Count the number of ones in it and store the result
back in AX. Repeat the process on the result (AX) until AX contains one. Calculate in
BX the number of iterations it took to make AX one. For example BX should contain 2
in the following case:
AX = 1100 0101 1010 0010 (input – 7 ones)
AX = 0000 0000 0000 0111 (after first iteration – 3 one)
AX = 0000 0000 0000 0011 (after second iteration – 2 one)
AX = 0000 0000 0000 0010 (after second iteration – 1 one)
AX = 0000 0000 0000 0001 STOP

3. Implement the following multiplication algorithm in Figure 8.1 (for unsigned numbers)
we discussed in class. Use n = 16

Page | 35
Lab Manual of Computer Organization and Architecture

Figure 8. 8

POST LAB:
Modify code of exercise – 3 to implement Booth’s algorithm.

Page | 36
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 9
SUBROUTINES AND STACK
OBJECTIVES
 To be able to write subroutines in assembly
 To understand basic concepts of stack

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY
In every processor, instructions are available to divert temporarily and to divert permanently.
The instructions for permanent diversion in 8088 are the jump instructions, while the
instruction for temporary diversion is the CALL instruction.

The CALL and RET Instructions


The call and ret instructions handle subroutine calls and returns. There are five different call
instructions and six different forms of the return instruction. The two major types are far and
near calls.

The near call instruction does the following:


It pushes the 16 bit offset of the next instruction following the call onto the stack.
It copies the 16 bit effective address into the ip register. Since the call instruction allows the
same addressing modes as jmp, call can obtain the target address using a relative,
memory, or register addressing mode.
Execution continues at the first instruction of the subroutine. This first instruction is the
opcode at the target address computed in the previous step.

The far call instruction does the following:


 It pushes the CS register onto the stack.
 It pushes the 16 bit offset of the next instruction following the call onto the stack.
 It copies the 32 bit effective address into the CS:IP registers. Since the call instruction
allows the same addressing modes as jmp, call can obtain the target address using a
relative, memory, or register addressing mode.
 Execution continues at the first instruction of the subroutine. This first instruction is
the opcode at the target address computed in the previous step.

The ret (return) instruction returns control to the caller of a subroutine. It does so by popping
the return address off the stack and transferring control to the instruction at this return address.

Page | 37
Lab Manual of Computer Organization and Architecture

The PUSH and POP Instructions


The 80x86 push and pop instructions manipulate data on the 80x86's hardware stack.
Following is an algorithmic description of each instruction:

Notice three things about the 80x86 hardware stack. First, it is always in the stack segment
(wherever SS points). Second, the stack grows down in memory. That is, as you push values
onto the stack the CPU stores them into successively lower memory locations. Finally, the
80x86 hardware stack pointer (SS:SP) always contains the address of the value on the top of
the stack (the last value pushed on the stack). You can use the 80x86 hardware stack for
temporarily saving registers and variables, passing parameters to a procedure, allocating
storage for local variables, and other uses.

Exercise
1. Write a subroutine “insert” to insert elements in an array "data" from a to b with
difference of c
a=ax, b=bx, c=cx

Your subroutine should store the previous context

Example.
a=1,b=10,c=2
insert(); // after calling the subroutine the array should be 1,3,5,7,9

a++
c++
insert(); // after calling the subroutine the array should be 2,5,8

2. PART – A:
Consider the following piece of code where 5 function (r1,r2,r3,r4,r5) are defined
Write a function “addtoset” that takes offset of each function and remembers this offset
in an array that can hold a maximum of 5 offsets. Write another function “callset” that
makes a call to all functions in the set one by one.

Page | 38
Lab Manual of Computer Organization and Architecture

PART- B:
Rewrite callset such that it does not use a CALL or a JMP to invoke the functions.
HINT: Setup the stack appropriately such that the RET will execute the first function,
its RET execute the next and so on till the last RET returns to the caller of “callset”

[org 0x0100]
….
jmp end

addtoSet:

ret

callSet:
….
ret

callByStack:
….
ret

r1:
add ax,0x0001
ret

r2:
add ax,0x0002
ret

r3:
add ax,0x0003
ret

r4:
add ax,0x0004
ret

r5:
add ax,0x0005
ret

Page | 39
Lab Manual of Computer Organization and Architecture

end:
mov ax, 0x4c00 ; terminate program
int 0x21
offsets: dw 0,0,0,0,0

Post Lab Exercise


1) Write code of two functions such that when one function is called the function
returns to second function after completion and when on second function it returns
back on first one after completion. Without using Jmp statement.

Page | 40
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 10
EXECUTION TIME
OBJECTIVES
 How to calculate the execution time for a piece of code.
 How to interpret the different execution times of various instructions.
 How to write efficient codes.
 How to evaluate a particular program with respect to its performance measure

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

Instruction cycle
The instruction cycle is the time period during which one instruction is fetched from memory
and executed when a computer is given an instruction in machine language. There are
typically five stages of an instruction cycle that the CPU carries out:
"Fetch the instruction" from memory. This step brings the instruction into the instruction
register, a circuit that holds the instruction so that it can be decoded and executed.

1. "Decode" the instruction.


2. "Read the effective address" from memory if the instruction has an indirect address.
3. "Execute" the instruction.
4. "Store" in memory any results generated by the operation, or send the results to an
output device.

Steps 1 and 2 are called the fetch cycle and are the same for each instruction. Steps 3 and 4
are called the execute cycle and will change with each instruction. The term refers to both
the series of four steps and also the amount of time that it takes to carry out the four steps.
An instruction cycle also is called a machine cycle and fetch-and-execute cycle.

Cycles per Instruction


Cycles per instruction', also known as clock cycles per instruction, or clocks per instruction
(CPI) is the number of clock cycles that happen when an instruction is being executed by a
computer with a given clock frequency. It can be taken as an average over a typical sequence
of instructions. In any case, it is better used when applied to RISC processors. In these
processors, theoretically, most instructions should be able to complete in one computer cycle.

Execution Time:
The execution time of a program consists of many factors, most of which are ignored (such as
waits for I/O, instruction fetch times, pipeline delays, etc.)
Page | 41
Lab Manual of Computer Organization and Architecture

Execution Time (processor-related) = IC x CPI x T


IC = instruction count
CPI = average number of system clock periods to execute an instruction
T = clock period
(Strictly speaking, (IC x CPI) should be the sum of the clock periods needed to execute each
instruction. Such info is usually provided by the manufacturers for each instruction in the
instruction set. Using the average makes things simpler)

Example:
Consider two programs having three types of instructions given as follows in table 10.1:
Table10.1

Compare both the programs for the following parameters


1. Instruction count
2. Speed of execution

Solution:

Instruction count IC.


IC for program 1 = 2 + 2 + 2 = 6
IC for program 2 = 1 + 5 + 1 = 7

For execution time we can use the following specifications.


ET = IC x CPI x T
ET1 = (2x2) + (2x3) + (2x4) = 18
ET2 = (5x2) + (1x3) + (1x4) = 17

(Note: Since both programs are executing on the same machine, the T factor can be ignored
while calculating ET.)

The instruction count for program 2 is higher than program 1. Still it runs faster than program
1 as obvious from the execution time calculation

This implies that we cannot use a single metric such as instruction count or CPI for measuring
the performance.

Page | 42
Lab Manual of Computer Organization and Architecture

When comparing two different machines, the factor T (time per clock cycle) must be taken
into consideration as well.

Exercise:
1. Find the execution time of the following codes:

Code -A
; sorting a list of three numbers using bubble sort
[ORG 0x0100]
JMP LOOP1
DATA: DB 10, 5, 6
MOV BX, 0x00

LOOP1:
MOV AL, [DATA+BX] ; LOAD NUMBER IN AX
CMP AL, [DATA+BX+1] ; COMPARE WITH NEXT NUMBER
JL NOSWAP ; NO SWAP IF ALREADY IN ORDER
MOV DL, byte[DATA+BX+1] ; LOAD SECOND ELEMENT IN DX
MOV byte [DATA+BX+1], AL ; STORE FIRST NUMBER IN SECOND
MOV byte [DATA+BX], DL ; STORE SECOND NUMBER IN FIRST

NOSWAP:
ADD BX, 1 ; ADVANCE BX TO NEXT INDEX
CMP BX, 2 ; ARE WE AT LAST INDEX
JNE LOOP1 ; IF NOT COMPARE NEXT TWO
MOV AX, 0X4C00 ; TERMINATE PROGRAM
INT 0X21

Code –B

[ORG 0x0100]
MOV BX, 0x00

start:
MOV AL, [DATA+BX] ; LOAD NUMBER IN AX
ADD AH,AL
ADD BX, 0x01
CMP BX, 0x0A
JNE start
MOV AX, 0X4C00 ; TERMINATE PROGRAM
INT 0X21
DATA: DB 1,2,3,4,5,6,7,8,9,10

Page | 43
Lab Manual of Computer Organization and Architecture

2. Write a program to find the GCD (Greatest common divisor) of two numbers M and
N, placed in the memory, according to following algorithm.
a. Divide M by N, getting Quotient Q and Remainder R.
b. If R = 0, Stop, N is the GCD of M and N.
c. If R ≠ 0, replace M by N and N by R and go to step (a).

Find the execution time of your program.


Post lab Exercise
Try to optimize the above problem to minimize its execution time.

Page | 44
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 11
USING BIOS SERVICES AND DOS FUNCTIONS
OBJECTIVES
The objective of this experiment is to introduce BIOS and DOS interrupt service routines to be
utilized in assembly language programs. In this experiment, you will use BIOS and DOS
services to write programs that can do the following: • Read a character/string from the
keyboard • Output a character/string to the display monitor • Clear the display screen • and
display cursor at a desired location on the screen

SOFTWARE TOOLS:

 Netwide Assembler NASM

THEORY

The Basic Input Output System (BIOS) is a set of x86 subroutines stored in Read-Only
Memory (ROM) that can be used by any operating system (DOS, Windows, Linux, etc) for
low-level input/output to various devices. Some of the services provided by BIOS are also
provided by DOS. In fact, a large number of DOS services make use of BIOS services. There
are different types of interrupts available which are divided into several categories as shown
below in table 11.1:

Table11. 1
BIOS and DOS interrupt routines provide a number of services that can be used to write
programs. These services include formatting disks, creating disk files, reading from or writing
to files, reading from keyboard, writing to display monitor, etc. The software interrupt
instruction INT is used for calling these services.

Positions on the screen are referenced using (row, column) coordinates. The upper left corner
has coordinates (0,0). For an 80 x 25 display, the rows are 0-24 and the columns are 0-79
shown in figure 11.1.

Page | 45
Lab Manual of Computer Organization and Architecture

Figure 11. 1

Commonly used DOS functions


DOS contains many functions that can be accessed by other application programs. These
functions are invoked using the assembly language instruction INT XX, where XX is replaced
by the number of the appropriate interrupt. Most of the available functions are invoked
through the INT 21H instruction.

Character input with echo (INT 21H, Function 01H): Reads a character from the standard
input device (usually the keyboard) and echoes it to the standard output device (usually the
display screen), or waits until a character is available. Example given in figure 11.2.

Figure 11. 2

Character input without echo (INT 21H, Function 07H): Reads a character from the
standard input device (usually the keyboard) without echoing it to the standard output device,
or waits until a character is available. This function can be used when you don’t want the input
characters to appear on the display, for example, in the case of password entry. Example given
in figure 11.3

Figure 11. 3

Page | 46
Lab Manual of Computer Organization and Architecture

Display Character (INT 21H, Function 02H): Displays a character at the standard output
device (usually the display screen). Example given in figure 11.4

Figure 11. 4

Exit program and return control to DOS (INT 21H, Function 4CH): Terminates current
process and returns control either to the parent process or DOS. Example given in figure 11.5

Figure 11. 5

Set Video Mode (INT 10H, Function 00H): Selects the video mode and clears the screen
automatically. Example given in figure 11.6

Figure 11. 6

Set Cursor Position (INT 10H, Function 02H): Sets the position of the display cursor by
specifying the character coordinates. Example given in figure 11.7

Figure 11. 7

Page | 47
Lab Manual of Computer Organization and Architecture

Problem
1. Write a code to read a key from the keyboard, and displays the next character on
screen. For example, if ‘e’ is pressed then ‘f’ is displayed
2. Write a code to clear screen, and displays following string. The string has a
background color = white and foreground color = black
“Hello World”
3. Write an assembly code that performs following functions
a. Clear the screen
b. Write “C” on screen at coordinates (12,40)
c. Wait for a key to be pressed ,
d. If a ‘L’ is pressed, display ‘Left’ on left of ‘C’ (output = Left C)
e. If a ‘R’ pressed, display ‘Right’ on right of ‘C’ (Output = Right C)

Page | 48
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 12
INSTRUCTION PIPELINE
OBJECTIVES
 Understanding instruction pipeline using MIPS Simulator
 To understand different pipeline hazards

SOFTWARE TOOLS:

 WINMIPS64 (MIPS program pipe-line simulator)

THEORY

WinMIPS64 Simulator
WinMIPS64 is a Windows based simulator of a pipelined implementation of the MIPS64 64-
bit processor. The user interface of simulator comprises a main window that appears with
seven child windows and a status line at the bottom. The seven child windows are Pipeline,
Code, Data, Registers, Statistics, Cycles and Terminal windows shown in Figure 12.1.

Figure 12. 1

You may refer to winmips64_Tutorial.pdf for detailed instructions to use this simulator.

Page | 49
Lab Manual of Computer Organization and Architecture

Instruction Pipelining

MIPS pipeline consists of five stages given in Figure 12.2. All stages are described in table
12.1

Figure 12. 2

Table12. 1

As, different instructions are present at different stages of the pipeline at any one clock cycle,
new registers are needed between each successive stages of the pipeline. These pipeline
registers contain all control information that is needed by that instruction. These registers are
referred to by the pair of stages:
• IF/ID
• ID/ALU
• ALU/MEM
• MEM/WB

If n is total number of instructions, each having k stages, and ?is the time of each stage then
execution time, speedup and throughput are defined as follows:

Execution time on non-pipelined computer is given as: tnp = nk?

Execution time on pipelined computer is given as: tp = (n+k-1)?

Speedup = tnp / tp

Page | 50
Lab Manual of Computer Organization and Architecture

Instruction Throughput (Non-Pipelined Execution) =


No. of instructions executed per unit time = IPC = n / tnp

Instruction Throughput (Pipelined Execution) =


No. of instructions executed per unit time = IPC = n / tp
Clocks per instruction (CPI) = 1/IPC

Pipeline Hazards

A pipeline hazard is a situation that prevents the next instruction in the instruction stream from
executing during its designated clock cycle. A pipeline hazard is a source of performance
degradation. There are three classes of hazards:

Structural Hazards:
They arise from resource conflicts when the hardware cannot support all possible
combinations of instructions in simultaneous overlapped execution.

Data Hazards:
They arise when an instruction depends on the result of a previous instruction in a way that is
exposed by the overlapping of instructions in the pipeline.

Control Hazards:
They arise from the pipelining of branches and other instructions that change the PC.

Exercise - 1
Save the code given in Figure 12.3 in \winmips64 folder with .s extension. Open command
prompt and compile it using command asmfilename.s. Open the .s file WinMIPS64. Simulate
the code step by step by pressing F7.

.data
A: .word 4
B: .word 5
C: .word 0
.text
main:
dadd r1, r2, r3 ;r1=r2+r3
dadd r6, r5, r4 ;r5 =r5+r4
halt

Figure 12. 3

A. Paste screenshot of pipeline.

Page | 51
Lab Manual of Computer Organization and Architecture

B. If this code is run for non-pipeline architecture, what would be the total execution
time?

C. If this code is run for non-pipeline architecture, what would be the throughput?

D. Calculate execution time for pipelined architecture.

E. Calculate speedup

F. Calculate IPC for pipeline architecture

G. Compare your solution with the result of simulator. Paste the statistics window here.

Exercise – 2

Consider the code given in figure 12.4


.data
A: .word 4
B: .word 5
C: .word 0
.text
main:
ld r2, A(r0) ; r2=A
ld r3, B(r0) ;r3=B
dadd r1, r2, r3 ;r1=r2+r3
dadd r6, r5, r4 ;r6=r5+r4
halt

Figure 12. 4

Page | 52
Lab Manual of Computer Organization and Architecture

A. Do you find any pipeline hazard(s) in this code? If yes, which one? Also, tell the cause
of hazard.

B. Simulate the code, and observe that how the hazard has been handled in the pipeline.
Paste the screenshot of the pipeline + statistics window.

Exercise – 3

Run the code given in figure 12.5. in the simulator and answer the following questions
.text
main:
ld r6, 0(r0) ; r6 =0
ld r4, 4(r1) ; r4=4
dsub r2, r6, r4 ;r2=r6-r4
dmul r2, r6, r1 ;r2=r6xr1
daddi r2, r2, 4 ;r2=r2+4
halt

Figure 12. 5

A. How many clock cycles were used by the code?

B. Note down the CPI?

C. How many pipeline hazards are there? Mention all the hazards with their causes.

Page | 53
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 13
STRING INSTRUCTIONS

OBJECTIVES
 To be able to use string instructions
 To be able to use index registers SI and DI for string operations.

SOFTWARE TOOLS:

 Netwide Assembler NASM


 Advanced Fullscreen Debugger (AFD)

THEORY

There are just 5 block processing instructions in 8088. In the primitiveform, the instructions
themselves operate on a single cell of memory at onetime. However a special prefix repeats
the instruction in hardware called theREP prefix. The REP prefix allows these instructions to
operate on a numberof data elements in one instruction. This is not like a loop; rather
thisrepetition is hard coded in the processor. The five instructions are STOS,LODS, CMPS,
SCAS, and MOVS called store string, load string, comparestring, scan string, and move string
respectively. MOVS is the instructionthat allows memory to memory moves, as was discussed
in the exceptions tothe memory to memory movement rules. String instructions are
complexinstruction in that they perform a number of tasks against one instruction.And with
the REP prefix they perform the task of a complex loop in oneinstruction. This causes drastic
speed improvements in operations on largeblocks of memory. The reduction in code size and
the improvement in speedare the two reasons why these instructions were introduced in the
8088processor.

There are a number of common things in these instructions. Firstly theyall work on a block of
data. DI and SI are used to access memory. SI and DIare called source index and destination
index because of string instructions.Whenever an instruction needs a memory source, DS:SI
holds the pointer toit. An override is possible that can change the association from DS but
thedefault is DS. Whenever a string instruction needs a memory destination,ES:DI holds the
pointer to it. No override is possible in this case. Whenever a byte register is needed, AL holds
the value. Whenever a word register is usedAX holds the value. For example STOS stores a
register in memory so AL orAX is the register used and ES:DI points to the destination. The
LODSinstruction loads from memory to register so the source is pointed to byDS:SI and the
register used is AL or AX.

String instructions work on a block of data. A block has a start and anend. The instructions can
work from the start towards the end and from theend towards the start. In fact they can work in
both directions, and theymust be allowed to work in both directions otherwise certain
operations withoverlapping blocks become impossible. This problem is discussed in

Page | 54
Lab Manual of Computer Organization and Architecture

detaillater. The direction of movement is controlled with the Direction Flag (DF) inthe flags
register. If this flag is cleared the direction is from lower addressestowards higher addresses
and if this flag is set the direction is from higheraddresses to lower addresses. If DF is cleared,
this is called the autoincrementmode of string instruction, and if DF is set, this is called the
autodecrementmode. There are two instructions to set and clear the directionflag.

cld ; clear direction flag


std ; set direction flag

Every string instruction has two variants; a byte variant and a wordvariant. For example the
two variants of STOS are STOSB and STOSW.Similarly the variants for the other string
instructions are attained byappending a B or a W to the instruction name. The operation of
each of thestring instructions and each of the repetition prefixes is discussed below.

REP Prefix
REP repeats the following string instruction CX times. The use of CX isimplied with the REP
prefix. The decrement in CX doesn’t affect any flags andthe jump is also independent of the
flags, just like JCXZ.
REPE and REPNE Prefixes
REPE or REPZ repeat the following string instruction while the zero flag isset and REPNE or
REPNZ repeat the following instruction while the zero flagis not set. REPE or REPNE are
used with the SCAS or CMPS instructions. The other string instructions have nothing to do
with the condition sincethey are performing no comparison. Also the initial state of flags
before thestring instruction does not affect the operation. The most complex operationof the
string instruction is with these prefixes.

STOS
STOS transfers a byte or word from register AL or AX to the string elementaddressed by
ES:DI and updates DI to point to the next location. STOS isoften used to clear a block of
memory or fill it with a constant.The implied source will always be in AL or AX. If DF is
clear, DI will beincremented by one or two depending on whether STOSB or STOSW is
used.If DF is set DI will be decremented by one or two depending on whetherSTOSB or
STOSW is used. If REP is used before this instruction, the processwill be repeated CX times.
CX is called the counter register because of thespecial treatment given to it in the LOOP and
JCXZ instructions and the REPset of prefixes. So if REP is used with STOS the whole block
of memory willbe filled with a constant value. REP will always decrement CX like the
LOOPinstruction and this cannot be changed with the direction flag. It is alsoindependent of
whether the byte or the word variant is used. It alwaysdecrements by one; therefore CX has
count of repetitions and not the countof bytes.

Page | 55
Lab Manual of Computer Organization and Architecture

Example 1: Clear Screen using STOS and REP instruction


; clear screen using string instructions
[org 0x0100]
jmp start
; subroutine to clear the screen
clrscr: push es
push ax
push cx
push di
mov ax, 0xb800
mov es, ax ; point es to video base
xor di, di ; point di to top left column
mov ax, 0x0720 ; space char in normal attribute
mov cx, 2000 ; number of screen locations
cld ; auto increment mode
rep stosw ; clear the whole screen
pop di
pop cx
pop ax
pop es
ret
start: call clrscr ; call clrscr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21

LODS
LODS transfers a byte or word from the source location DS:SI to AL or AXand updates SI to
point to the next location. LODS is generally used in a loopand not with the REP prefix since
the value previously loaded in the registeris overwritten if the instruction is repeated and only
the last value of theblock remains in the register.

Example 2: Print “Hello World using LODS, STOS instructions.

; hello world printing using string instructions


[org 0x0100]
jmp start
message: db 'hello world' ; string to be printed
length: dw 11 ; length of string
;;;;; COPY LINES 005-024 FROM EXAMPLE 6.5 (clrscr) ;;;;;
; subroutine to print a string
; takes the x position, y position, attribute, address of string and
; its length as parameters
printstr: push bp

Page | 56
Lab Manual of Computer Organization and Architecture

mov bp, sp
push es
push ax
push cx
push si
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+10] ; multiply with y position
add ax, [bp+12] ; add x position
shl ax, 1 ; turn into byte offset
mov di,ax ; point di to required location
mov si, [bp+6] ; point si to string
mov cx, [bp+4] ; load length of string in cx
mov ah, [bp+8] ; load attribute in ah
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 10
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
push word [length] ; push message length
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21

P.S: clrscr function is used from example 1

Page | 57
Lab Manual of Computer Organization and Architecture

SCAS
SCAS compares a source byte or word in register AL or AX with thedestination string element
addressed by ES:DI and updates the flags. DI isupdated to point to the next location. SCAS is
often used to locate equality orin-equality in a string through the use of an appropriate
prefix.SCAS is a bit different from the other instructions. This is more like theCMP
instruction in that it does subtraction of its operands. The prefixesREPE (repeat while equal)
and REPNE (repeat while not equal) are used withthis instruction. The instruction is used to
locate a byte in AL in the block ofmemory. When the first equality or inequality is
encountered; both haveuses. For example this instruction can be used to search for a 0 in a
nullterminated string to calculate the length of the string. In this form REPNEwill be used to
repeat while the null is not there.
Example 3: ; Printing “hello world” with a null terminated string
; hello world printing with a null terminated string
[org 0x0100]
jmp start
message: db 'hello world', 0 ; null terminated string
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
; subroutine to print a string
; takes the x position, y position, attribute, and address of a null
; terminated string as parameters
printstr: push bp
mov bp, sp
push es
push ax
push cx
push si
push di
push ds
pop es ; load ds in es
mov di, [bp+4] ; point di to string
mov cx, 0xffff ; load maximum number in cx
xor al, al ; load a zero in al
repne scasb ; find zero in the string
mov ax, 0xffff ; load maximum number in ax
sub ax, cx ; find change in cx
dec ax ; exclude null from length
jz exit ; no printing if string is empty
mov cx, ax ; load string length in cx
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+8] ; multiply with y position
add ax, [bp+10] ; add x position

Page | 58
Lab Manual of Computer Organization and Architecture

shl ax, 1 ; turn into byte offset


mov di,ax ; point di to required location
mov si, [bp+4] ; point si to string
mov ah, [bp+6] ; load attribute in ah
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
exit: pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 8
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21

MOVS
MOVS transfers a byte or word from the source location DS:SI to thedestination ES:DI and
updates SI and DI to point to the next locations.MOVS is used to move a block of memory.
The DF is important in the case ofoverlapping blocks. For example when the source and
destination blocksoverlap and the source is below the destination copy must be done
upwardswhile if the destination is below the source copy must be done downwards.We cannot
perform both these copy operations properly if the direction flagwas not provided. If the
source is below the destination and an upwards copyis used the source to be copied is
destroyed. If however the copy is donedownwards the portion of source destroyed is the one
that has already been copied. Therefore we need the control of the direction flag to handle
thisproblem.

CMPS

Page | 59
Lab Manual of Computer Organization and Architecture

CMPS subtracts the source location DS:SI from the destination locationES:DI. Source and
Destination are unaffected. SI and DI are updatedaccordingly. CMPS compares two blocks of
memory for equality or inequalityof the block. It subtracts byte by byte or word by word. If
used with a REPEor a REPNE prefix is repeats as long as the blocks are same or as long
asthey are different. For example it can be used for find a substring. Asubstring is a string that
is contained in another string. For example “has” iscontained in “Mary has a little lamp.”
Using CMPS we can do the operation ofa complex loop in a single instruction. Only the REPE
and REPNE prefixesare meaningful with this instruction.

Problems:

1. Write a strcmp function to compare two strings using string instructions.

2. Write a strcpy function to copy the larger string found in above function in to memory
location named Larger and copy the smaller string in the memory location named
smallerusing string instructions.

3. Write a strlen function to find the lengthof given string using string instructions.

Page | 60
Lab Manual of Computer Organization and Architecture

EXPERIMENT- 14
MULTITASKING
OBJECTIVE:
To run two tasking using timer interrupt and observing their
multitasking behavior.
SOFTWARE TOOLS:

 Netwide Assembler NASM

THEORY:
If we have two different programs A and B. Program A is broken, its state saved, and returned
to B instead of A. By looking at the instruction set, we can immediately say that nothing can
stop us from doing that.
IRET will return to whatever CS and IP it finds on the stack. Now B is interrupted somehow,
its state saved, and we return back to A. A will have no way of knowing that it was interrupted
as its entire environment has been restored. It never knew the debugger took control when it
was debugged. It sill has no way of gaining this knowledge. If this work of breaking and
restoring programs is done at high speed the user will feel that all the programs are running at
the same time where actually they are being switched to and forth at high speed.

We have to Hook timer interrupt for Multitasking.

EXAMPLE 14.1

The example given in Figure 14.1 shows how we can change flow of execution form one task
to another. The two subroutines rotate bars by changing characters at the two corners of the
screen and have infinite loops. By hooking the timer interrupts and saving and restoring the
registers of the tasks one by one, it appears that both tasks are running simultaneously.

Page | 61
Lab Manual of Computer Organization and Architecture

Page | 62
Lab Manual of Computer Organization and Architecture

Figure 14. 1

Question: Insert another task in above example that displays the rotating bar in the center of
the screen on first row. (Now total three rotating bars will be displayed on the screen
simultaneously).

Post lab Exercise

Write two tasks first task is an up counter and second is a down counter. Now run the tasks
using multitasking and show the result of up counter at Screen top left corner and result of
down counter at top left corner.

Page | 63
Lab Manual of Computer Organization and Architecture

Appendix A: Lab Evaluation Criteria

Labs with projects


1. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%
2. Quizzes (3-4) 15%
3. Final evaluation 35%
a. Project Implementation 60%
b. Project report and quiz 40%

Labs without projects


4. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%
5. Quizzes (3-4) 20%
6. Final Evaluation 30%
i. Experiment 60%
ii. Lab report, pre and post
experiment quiz 40%

Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of
copying may entail ZERO in that experiment. Second instance of copying may be reported to
DC. This may result in awarding FAIL in the lab course.

Page | 64
Lab Manual of Computer Organization and Architecture

Appendix B: Safety around Electricity


In all the Electrical Engineering (EE) labs, with an aim to prevent any unforeseen accidents
during conduct of lab experiments, following preventive measures and safe practices shall be
adopted:

 Remember that the voltage of the electricity and the available electrical current in EE
labs has enough power to cause death/injury by electrocution. It is around 50V/10 mA
that the “cannot let go” level is reached. “The key to survival is to decrease our
exposure to energized circuits.”
 If a person touches an energized bare wire or faulty equipment while grounded,
electricity will instantly pass through the body to the ground, causing a harmful,
potentially fatal, shock.
 Each circuit must be protected by a fuse or circuit breaker that will blow or “trip”
when its safe carrying capacity is surpassed. If a fuse blows or circuit breaker trips
repeatedly while in normal use (not overloaded), check for shorts and other faults in
the line or devices. Do not resume use until the trouble is fixed.
 It is hazardous to overload electrical circuits by using extension cords and multi-plug
outlets. Use extension cords only when necessary and make sure they are heavy
enough for the job. Avoid creating an “octopus” by inserting several plugs into a multi-
plug outlet connected to a single wall outlet. Extension cords should ONLY be used on
a temporary basis in situations where fixed wiring is not feasible.
 Dimmed lights, reduced output from heaters and poor monitor pictures are all
symptoms of an overloaded circuit. Keep the total load at any one time safely below
maximum capacity.
 If wires are exposed, they may cause a shock to a person who comes into contact with
them. Cords should not be hung on nails, run over or wrapped around objects, knotted
or twisted. This may break the wire or insulation. Short circuits are usually caused by
bare wires touching due to breakdown of insulation. Electrical tape or any other kind
of tape is not adequate for insulation!
 Electrical cords should be examined visually before use for external defects such as:
Fraying (worn out) and exposed wiring, loose parts, deformed or missing parts,
damage to outer jacket or insulation, evidence of internal damage such as pinched or
crushed outer jacket. If any defects are found the electric cords should be removed
from service immediately.
 Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
 Plug your heavy current consuming or any other large appliances into an outlet that is
not shared with other appliances. Do not tamper with fuses as this is a potential fire
hazard. Do not overload circuits as this may cause the wires to heat and ignite
insulation or other combustibles.
 Keep lab equipment properly cleaned and maintained.
 Ensure lamps are free from contact with flammable material. Always use lights bulbs
with the recommended wattage for your lamp and equipment.
 Be aware of the odor of burning plastic or wire.
 ALWAYS follow the manufacturer recommendations when using or installing new lab
equipment. Wiring installations should always be made by a licensed electrician or
other qualified person. All electrical lab equipment should have the label of a testing
laboratory.

Page | 65
Lab Manual of Computer Organization and Architecture

 Be aware of missing ground prong and outlet cover, pinched wires, damaged casings
on electrical outlets.
 Inform Lab engineer / Lab assistant of any failure of safety preventive measures and
safe practices as soon you notice it. Be alert and proceed with caution at all times in
the laboratory.
 Conduct yourself in a responsible manner at all times in the EE Labs.
 Follow all written and verbal instructions carefully. If you do not understand a
direction or part of a procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT
BEFORE PROCEEDING WITH THE ACTIVITY.
 Never work alone in the laboratory. No student may work in EE Labs without the
presence of the Lab engineer / Lab assistant.
 Perform only those experiments authorized by your teacher. Carefully follow all
instructions, both written and oral. Unauthorized experiments are not allowed.
 Be prepared for your work in the EE Labs. Read all procedures thoroughly before
entering the laboratory. Never fool around in the laboratory. Horseplay, practical
jokes, and pranks are dangerous and prohibited.
 Always work in a well-ventilated area.
 Observe good housekeeping practices. Work areas should be kept clean and tidy at all
times.
 Experiments must be personally monitored at all times. Do not wander around the
room, distract other students, startle other students or interfere with the laboratory
experiments of others.
 Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or
baggy clothing are a hazard in the laboratory. Long hair must be tied back, and
dangling jewelry and baggy clothing must be secured. Shoes must completely cover
the foot.
 Know the locations and operating procedures of all safety equipment including fire
extinguisher. Know what to do if there is a fire during a lab period; “Turn off
equipment, if possible and exit EE lab immediately.”

Page | 66
Lab Manual of Computer Organization and Architecture

Appendix C: Guidelines on Preparing Lab Reports


Each student will maintain a lab notebook for each lab course. He will write a report for each
experiment he performs in his notebook. A format has been developed for writing these lab
reports.

Lab Report Format


1. Introduction: Introduce the new constructs/ commands being used, and their
significance.
2. Objective: What are the learning goals of the experiment?
3. Design: How do the new constructs facilitate achievement of the objectives; if
possible, a comparison in terms of efficacy and computational tractability with the
alternate constructs? Include the circuit diagram and code with explanation.
4. Issues: The bugs encountered and the way they were removed.
5. Conclusions: What conclusions can be drawn from experiment?
6. Application: Suggest a real world application where this exercise may apply.
7. Answers to post lab questions (if any).

Sample Lab Report for Programming Labs

Introduction

The ability to control the flow of the program, letting it make decisions on what code to
execute, is important to the programmer. The if-else statement allows the programmer to
control if a program enters a section of code or not based on whether a given condition is true
or false. If-else statements control conditional branching.

if ( expression )
statement1
else
statement2

If the value of expression is nonzero, statement1 is executed. If the optional else is present,
statement2 is executed if the value of expression is zero. In this lab, we use this construct to
select an action based upon the user's input, or a predefined parameter.

Page | 67
Lab Manual of Computer Organization and Architecture

Objective:

To use if-else statements for facilitation of programming objectives: A palindrome is a number


or a text phrase that reads the same backward as forward. For example, each of the following
five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. We have written a C++
program that reads in a five-digit integer and determines whether it is a palindrome.

Design:

Code with explanation:

The objective was achieved with the following code:

#include<iostream>

Usingnamespacestd;
Intmain()
{
inti,temp,d,revrs=0;

cout<<"enter the number to check :";


cin>>i;
temp=i;
while(temp>0)
{
d=temp%10;
temp/=10;
revrs=revrs*10+d;

}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";

}
}

Screen shots of the output for various inputs are shown in Figure 2:

Fig.2. Screen shot of the output

The conditional statement made this implementation possible; without conditional branching,
it is not possible to achieve this objective.

Page | 68
Lab Manual of Computer Organization and Architecture

Issues:

Encountered bugs and issues; how were they identified and resolved.

Conclusions:

The output indicates correct execution of the code.

Applications:

If-else statements are a basic construct for programming to handle decisions.

Answers of Post Lab Questions:

Page | 69

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy