0% found this document useful (0 votes)
7 views

Micro_computer_assignment_group1

Micro_computer_assignment_group1

Uploaded by

ezekiel nyamu
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)
7 views

Micro_computer_assignment_group1

Micro_computer_assignment_group1

Uploaded by

ezekiel nyamu
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/ 48

THE UNITED AFRICA UNIVERSITY OF TANZANIA

PROGRAM: BACHELOR OF SCIENCE IN COMPUTER ENGINEERING AND IT


COURSE: MICRO COMPUTER SYSTEMS 1
INSTRACTOR: EZEKIEL OGAKHAN NYAMU
CODE: CS 214
TASK: GROUP ASSIGNMENT
SUBMISION DATE: 13rd December 2024

S/No FULL NAME REG NO MARKS

1 JACKLINE LWENA 23011008

2 MELCHIZEDEKI GASTO 23011014

3 EMMANUEL SAITOTI 23011003

4 RASHIDI JUMA 23011016

5 SAMSON PATRICK 23011017

1
Contents
Task 1.1.................................................................................................................................................... 4
Essential Components of an Instruction Set ............................................................................................ 4
How These Components Shape Assembly Language Programs? ............................................................ 5
Task 1.2.................................................................................................................................................... 6
Assembly Language Program .................................................................................................................. 6
Explanation of Each Instruction ............................................................................................................... 7
Task 2.1.................................................................................................................................................... 8
Investigating Addressing Modes in Assembly Language ......................................................................... 8
Significance in Efficient Programming ..................................................................................................... 8
Examples from Modern Processors......................................................................................................... 9
Task 2.2.................................................................................................................................................. 10
Assembly Language Program ................................................................................................................ 10
Explanation of Addressing Modes. ........................................................................................................ 11
Task 3.1.................................................................................................................................................. 12
Assembly Language Program ................................................................................................................ 12
Step-by-Step Explanation ...................................................................................................................... 13
Task 3.2.................................................................................................................................................. 15
Assembly Language Program ................................................................................................................ 15
Pseudocode. .......................................................................................................................................... 16
Flowchart............................................................................................................................................... 17
Task 4.1.................................................................................................................................................. 18
Assembly Language Program ................................................................................................................ 18
Documentation of the Loop Structure and Control............................................................................... 19
Task 4.2.................................................................................................................................................. 21
Assembly Language Program ................................................................................................................ 21
Explanation of Nested Loops. ................................................................................................................ 23
Task 5.1.................................................................................................................................................. 24
Methods for Data Transfer .................................................................................................................... 24
Relevant Instructions in Assembly Language. ....................................................................................... 25
Conclusion ............................................................................................................................................. 26
Task 5.2.................................................................................................................................................. 26
Assembly Language Program ................................................................................................................ 26
Explanation of Program Logic and Execution ........................................................................................ 27
Task 6.1.................................................................................................................................................. 29
Concept of Interrupts in Assembly Language. ....................................................................................... 29

2
Role and Importance in System Operation ........................................................................................... 29
Types of Interrupts. ............................................................................................................................... 30
Example of an Interrupt in Assembly Language. ................................................................................... 30
Explanation ............................................................................................................................................ 31
Task 6.2.................................................................................................................................................. 32
Assembly Language Program ................................................................................................................ 32
Task 7.1.................................................................................................................................................. 35
Project: Number Guessing Game in Assembly Language. ..................................................................... 36
Assembly Language Program ................................................................................................................ 36
Task 7.2.................................................................................................................................................. 41
Project: Guess the Number Game in Assembly Language..................................................................... 41
Program Logic. ....................................................................................................................................... 41
Assembly Language Progra.................................................................................................................... 42
Flowchart............................................................................................................................................... 46
Challenges Faced and Solutions. ........................................................................................................... 47
references.............................................................................................................................................. 48

3
Task 1.1:
Identify and describe the essential components of an instruction set. Discuss how these components
shape the structure and functionality of assembly language programs. Include examples from
modern processors.

Essential Components of an Instruction Set.


1. Operation Code (Opcode):

- Description: The opcode specifies the operation to be performed by the processor. It's
essentially the command part of the instruction, like ADD for addition or MOV for data
transfer.

- Example: In the x86 architecture, `ADD eax, ebx` adds the values in registers `eax` and
`ebx`.

2. Operand(s):

- Description: Operands are the data items that the instruction manipulates. They can be
immediate values, registers, or memory addresses.

- Example: In `MOV eax, [ebx+4] `, `eax` and `[ebx+4] ` are operands, where `eax` is a
register and `[ebx+4] ` is a memory address.

3. Addressing Mode:

- Description: Addressing modes specify how the operand is accessed. Common modes
include immediate, register, direct, and indirect addressing.

- Example: `MOV eax, [ebx]` uses indirect addressing, where the memory address is
determined by the value in `ebx`.

4. Instruction Format:

- Description: The instruction format is the layout of bits in an instruction. It typically


includes fields for the opcode, operands, and addressing modes.

4
- Example: In the RISC-V architecture, a typical instruction format might include 7 bits for
the opcode, 5 bits for each of the two source registers, and 5 bits for the destination register.

5. Instruction Length:

- Description: This is the size of the instruction, which can be fixed or variable. RISC
architectures generally use fixed-length instructions, while CISC architectures may have
variable-length instructions.

- Example: ARM (a RISC architecture) typically uses 32-bit fixed-length instructions,


while x86 (a CISC architecture) can have instructions ranging from 1 to 15 bytes.

How These Components Shape Assembly Language Programs?


- Opcode and Operand Structure: The combination of opcodes and operands determines the
types of operations that can be performed and how data is manipulated within a program. For
example, arithmetic operations, data movement, and control instructions (like jumps and
branches) all rely on these components.

- Addressing Modes: These provide flexibility in how instructions access data, allowing for
more complex data structures and efficient use of memory. Indirect and indexed addressing
modes, for example, enable efficient access to array elements.

- Instruction Format and Length: These factors influence the complexity of the assembly
language. A simpler, fixed-format instruction set (like in RISC architectures) leads to more
predictable performance and easier optimization. Conversely, the more complex, variable-
length instructions in CISC architectures allow for more powerful and compact code.

5
Task 1.2:
Create an assembly language program that demonstrates at least five distinct types of instructions,
such as data transfer, arithmetic, logic, control, and comparison. Document and explain the purpose
of each instruction used.

Assembly Language Program


section .data

num1 db 10 ; Declare a byte with value 10

section .bss

result resb 1 ; Reserve a byte for the result

section .text

global _star

_start:

; Data Transfer Instruction

mov al, [num1] ; Move the value at address num1 (10) into register al

; Arithmetic Instruction

add al, 5 ; Add 5 to the value in register al (al = 10 + 5 = 15)

; Logic Instruction

and al, 0Fh ; Perform a bitwise AND on al with 0Fh (binary: 00001111)

; Result: al = 15 AND 15 = 15 (binary: 1111)

; Comparison Instruction

cmp al, 15 ; Compare the value in al with 15

; Sets the zero flag if al is equal to 15

; Control Instruction

je equal ; Jump to label 'equal' if the comparison was equal (zero flag set)

6
; Move the result to the reserved memory location

mov [result], al ; Store the result (15) in the variable 'result'

equal:

; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call the kernel to exit

Explanation of Each Instruction.


1. Data Transfer Instruction: `mov al, [num1] `

- Purpose: Move the value stored at memory address `num1` (which is 10) into the `al`
register.

- Explanation: This instruction transfers data from a memory location to a register. It's
essential for loading values into registers for further processing.

2. Arithmetic Instruction: `add al, 5`

- Purpose: Add the immediate value 5 to the value in the `al` register.

- Explanation: This performs an arithmetic operation (addition) on the contents of a


register. Arithmetic instructions are fundamental for calculations.

3. Logic Instruction: `and al, 0Fh`

- Purpose: Perform a bitwise AND operation on the contents of the `al` register with `0Fh`.

- Explanation: Logic instructions like AND are used to manipulate specific bits within a
byte or word. This operation is often used for masking certain bits.

4. Comparison Instruction: `cmp al, 15`

7
- Purpose: Compare the value in the `al` register with the immediate value 15.

- Explanation: The CMP instruction sets the processor's flags based on the result of the
comparison. It's used for decision-making in programs.

5. Control Instruction: `je equal`

- Purpose: Jump to the label `equal` if the zero flag is set (i.e., if `al` equals 15).

- Explanation: Control instructions like JUMP direct the flow of execution in a program.
This allows for conditional execution of code blocks based on previous comparisons or
calculations.

Task 2.1:
Investigate and explain the concept of addressing modes in assembly language. Highlight their
significance in efficient programming with examples.

Investigating Addressing Modes in Assembly Language.


Addressing modes in assembly language are methods used to specify operands (data) for
instructions. These modes determine how the processor should interpret the operand specified
in the instruction. Understanding addressing modes is crucial for efficient programming, as
they can significantly influence the performance and flexibility of code.

Significance in Efficient Programming.


- Speed: Register and immediate addressing modes are the fastest because they involve
minimal memory access. Efficient use of these modes can lead to faster program execution.

- Flexibility: Indirect, indexed, and base-indexed addressing modes provide flexibility in


accessing memory. They are essential for working with arrays, pointers, and dynamic data
structures.

- Memory Efficiency: Using appropriate addressing modes can minimize memory usage and
increase the efficiency of memory accesses. This is especially important in embedded
systems and applications with limited resources.

8
- Code Readability and Maintenance: Proper use of addressing modes can make the code
more readable and easier to maintain. For example, using indexed addressing for arrays
makes it clear that you are accessing array elements.

Examples from Modern Processors


1. Immediate Addressing:

```assembly

MOV AL, 10 ; Move immediate value 10 into AL

```

2. Register Addressing:

```assembly

MOV AX, CX ; Move value from CX to AX

```

3. Direct Addressing:

```assembly

MOV AX, [1234h] ; Move value from memory address 1234h to AX

```

4. Indirect Addressing:

```assembly

MOV AX, [BX] ; Move value from address in BX to AX

```

5. Indexed Addressing:

```assembly

MOV AX, [BX + SI] ; Move value from address (BX + SI) to AX

```

9
6. Base-Indexed Addressing:

```assembly

MOV AX, [BX + SI + 4] ; Move value from address (BX + SI + 4) to AX

```

Task 2.2:
Write an assembly program that incorporates and demonstrates direct, indirect, and immediate
addressing modes. Provide a detailed explanation for the functionality and usage of each mode
within your program

Assembly Language Program


```assembly

section .data

num1 db 10 ; Define a byte with the value 10

num2 db 20 ; Define a byte with the value 20

section .bss

result resb 1 ; Reserve a byte for storing the result

section .text

global _start

_start:

; Immediate Addressing Mode

mov al, 5 ; Move the immediate value 5 into the AL register

; Direct Addressing Mode

mov bl, [num1] ; Move the value at address of num1 (10) into the BL register

; Indirect Addressing Mode

mov ecx, num2 ; Load the address of num2 into the ECX register

mov dl, [ecx] ; Move the value at the address in ECX (20) into the DL register

10
; Perform an operation using the loaded values

add al, bl ; AL = AL + BL (5 + 10 = 15)

add al, dl ; AL = AL + DL (15 + 20 = 35)

; Store the result in the reserved memory location

mov [result], al ; Move the value in AL (35) into the result variable

; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call the kernel to exit

```

Explanation of Addressing Modes.


1. Immediate Addressing Mode:

- Instruction: `mov al, 5`

- Functionality: Moves the immediate value `5` directly into the `AL` register.

- Usage: Immediate addressing is used when you need to work with a constant value. It is
fast because the value is embedded directly in the instruction.

- Example: Here, `5` is the immediate value, and it is moved into `AL`.

2. Direct Addressing Mode:

- Instruction: `mov bl, [num1]`

- Functionality: Moves the value stored at the memory address `num1` (which is `10`) into
the `BL` register.

- Usage: Direct addressing is used to access specific memory locations. It is straightforward


and useful for static data.

- Example: The value `10` at the address `num1` is directly moved into `BL`.

11
3. Indirect Addressing Mode:

- Instruction: `mov ecx, num2` and `mov dl, [ecx]`

- Functionality: First, the address of `num2` is moved into the `ECX` register. Then, the
value at the address contained in `ECX` (which is `20`) is moved into the `DL` register.

- Usage: Indirect addressing is used for accessing memory addresses dynamically. It is


powerful for working with arrays and pointers.

- Example: The value `20` at the address `num2` is accessed indirectly through the `ECX`
register and moved into `DL`.

Task 3.1:
Develop an assembly program to compute the factorial of a given number using simple
arithmetic instructions. Include a step-by-step explanation of your code.

Assembly Language Program.


```assembly

section .data

num db 5 ; Number to compute the factorial of (change this value as needed)

result dw 1 ; Initialize result to 1 (factorial of 0 is 1)

section .text

global _start

_start:

; Load the number into a register

mov al, [num] ; Load the value of num into AL register

mov bl, al ; Copy the value to BL (to use in loop)

; Initialize result to 1

12
mov cx, 1 ; Move 1 to CX register

factorial_loop:

; Multiply CX by BL and store the result in CX

mul cx ; Multiply AL by CX, result is in AX

mov cx, ax ; Store result back in CX

; Decrement BL

dec bl ; BL = BL - 1

; If BL is not zero, repeat the loop

cmp bl, 1 ; Compare BL with 1

jg factorial_loop ; If BL > 1, jump to factorial_loop

; Store the final result

mov [result], cx ; Store the factorial result in memory

; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call the kernel to exit

```

Step-by-Step Explanation.
1. Data Section:

- `num db 5`: This defines a byte-sized variable `num` with the value 5. You can change
this value to compute the factorial of a different number.

- `result dw 1`: This initializes a word-sized variable `result` to 1. The factorial of 0 is 1, so


we start with 1.

2. Text Section:

13
- The program starts with `_start`, which is the entry point.

3. Loading the Number:

- `mov al, [num]`: Load the value of `num` (5) into the `AL` register.

- `mov bl, al`: Copy the value from `AL` to `BL`. `BL` will be used as a counter in the loop.

4. Initialize Result:

- `mov cx, 1`: Initialize the `CX` register to 1. This will hold the intermediate results of the
factorial calculation.

5. Factorial Loop:

- `factorial_loop:`: Label marking the start of the loop.

- `mul cx`: Multiply `AL` (which holds the current number) by `CX`. The result is stored in
`AX`.

- `mov cx, ax`: Store the result back in `CX`.

- `dec bl`: Decrement the value of `BL` by 1.

- `cmp bl, 1`: Compare `BL` with 1.

- `jg factorial_loop`: If `BL` is greater than 1, jump back to `factorial_loop` to continue the
calculation.

6. Storing the Result:

- `mov [result], cx`: Store the final factorial result from `CX` into the `result` variable.

7. Exiting the Program:

- `mov eax, 1`: Prepare the system call number for exiting the program.

- `xor ebx, ebx`: Set the exit code to 0.

- `int 0x80`: Make the system call to exit the program.

14
Task 3.2
: Create an assembly program that performs the logic operations: AND, OR, XOR, and NOT.
Accompany your program with a flowchart or pseudocode to clarify the logic behind each
operation.

Assembly Language Program.


```assembly

section .data

val1 db 0b10101010 ; Binary value 10101010

val2 db 0b11001100 ; Binary value 11001100

section .bss

result_and resb 1

result_or resb 1

result_xor resb 1

result_not resb 1

section .text

global _start

_start:

; Perform AND operation

mov al, [val1]

and al, [val2]

mov [result_and], al

; Perform OR operation

mov al, [val1]

or al, [val2]

mov [result_or], al

; Perform XOR operation

15
mov al, [val1]

xor al, [val2]

mov [result_xor], al

; Perform NOT operation

mov al, [val1]

not al

mov [result_not], al

; Exit program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call kernel to exit

```

Pseudocode.
```plaintext

1. Initialize val1 to binary 10101010

2. Initialize val2 to binary 11001100

3. Perform AND operation:

a. Load val1 into register A

b. AND register A with val2

c. Store the result in result_and

4. Perform OR operation:

a. Load val1 into register A

16
b. OR register A with val2

c. Store the result in result_or

5. Perform XOR operation:

a. Load val1 into register A

b. XOR register A with val2

c. Store the result in result_xor

6. Perform NOT operation:

a. Load val1 into register A

b. NOT register A

c. Store the result in result_not

7. Exit the program

```

Flowchart.
Here's a flowchart to visualize the logic operations:

1. Start

2. Load val1 into register A

3. Perform AND operation

- AND A with val2

- Store result in result_and

4. Load val1 into register A

17
5. Perform OR operation

- OR A with val2

- Store result in result_or

6. Load val1 into register A

7. Perform XOR operation

- XOR A with val2

- Store result in result_xor

8. Load val1 into register A

9. Perform NOT operation

- NOT A

- Store result in result_not

10. Exit the program

Task 4.1
: Write an assembly program that calculates the sum of integers from 1 to NNN using a loop.
Document how the loop is structured and controlled within the program.

Assembly Language Program.


```assembly

section .data

N db 10 ; Define the upper limit N (change this value as needed)

sum dw 0 ; Variable to store the sum

section .bss

section .text

global _start

_start:

18
; Initialize registers

mov cx, 1 ; CX register will serve as the counter, starting from 1

mov bx, 0 ; BX register will be used to accumulate the sum

calculate_sum:

add bx, cx ; Add the current value of CX to BX (sum = sum + counter)

inc cx ; Increment the counter (CX = CX + 1)

cmp cx, [N] ; Compare the counter (CX) with N

jle calculate_sum; If CX <= N, repeat the loop

; Store the result in the sum variable

mov [sum], bx

; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call the kernel to exit

```

Documentation of the Loop Structure and Control.


1. Initialization:

- Instruction: `mov cx, 1`

- Purpose: Initialize the `CX` register to 1. This register serves as the counter, starting from
1.

- Instruction: `mov bx, 0`

- Purpose: Initialize the `BX` register to 0. This register will be used to accumulate the sum.

2. Loop Label (calculate_sum):

19
- Instruction: `calculate_sum:`

- Purpose: This label marks the beginning of the loop. It is used as a reference point for the
loop control instructions.

3. Addition Operation:

- Instruction: `add bx, cx`

- Purpose: Add the current value of `CX` (the counter) to `BX` (the accumulator). This
operation updates the sum by adding the current counter value.

4. Increment Counter:

- Instruction: `inc cx`

- Purpose: Increment the `CX` register by 1. This updates the counter for the next iteration
of the loop.

5. Comparison:

- Instruction: `cmp cx, [N]`

- Purpose: Compare the current value of `CX` with `N`. This checks if the counter has
reached the upper limit.

6. Loop Control:

- Instruction: `jle calculate_sum`

- Purpose: If `CX` is less than or equal to `N`, jump back to the `calculate_sum` label to
repeat the loop. This ensures that the loop continues as long as the counter is within the
desired range.

7. Store the Result:

20
- Instruction: `mov [sum], bx`

- Purpose: After the loop completes, store the final sum from `BX` into the `sum` variable.

8. Exit the Program:

- Instruction: `mov eax, 1`, `xor ebx, ebx`, `int 0x80`

- Purpose: These instructions perform a system call to exit the program with exit code 0.

Task 4.2:
Design an assembly program with nested loops to generate a multiplication table for
numbers 1 to 10. Include comments to explain the logic of each nested loop.

Assembly Language Program.


```assembly

section .data

table db 10, 10 ; Dimensions of the multiplication table (10x10)

section .bss

result resb 100 ; Reserve space for storing the multiplication table (10x10)

section .text

global _start

_start:

; Outer loop: Iterate over rows (1 to 10)

mov cx, 1 ; Initialize outer loop counter (rows) to 1

outer_loop:

cmp cx, 11 ; Compare counter with 11 (10 + 1)

jge end_outer_loop ; If counter >= 11, exit the outer loop

21
; Inner loop: Iterate over columns (1 to 10)

mov dx, 1 ; Initialize inner loop counter (columns) to 1

inner_loop:

cmp dx, 11 ; Compare counter with 11 (10 + 1)

jge end_inner_loop ; If counter >= 11, exit the inner loop

; Calculate multiplication (row * column)

mov ax, cx ; Move outer loop counter (row) to AX

mul dx ; Multiply AX by inner loop counter (column)

; Store result in the appropriate position in the result array

mov bx, 10 ; Move 10 to BX (number of columns)

mul bx ; AX = row * 10

add ax, dx ; AX = (row * 10) + column

dec ax ; Adjust index to be zero-based

; Store result

mov [result + ax], al ; Store result in memory

; Increment inner loop counter (columns)

inc dx ; DX = DX + 1

jmp inner_loop ; Jump back to the start of the inner loop

end_inner_loop:

; Increment outer loop counter (rows)

inc cx ; CX = CX + 1

jmp outer_loop ; Jump back to the start of the outer loop

end_outer_loop:

22
; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call kernel to exit

```

Explanation of Nested Loops.


1. Outer Loop:

- Initialization: `mov cx, 1`

- Initialize the outer loop counter (rows) to 1.

-Comparison: `cmp cx, 11`

- Compare the counter with 11. The loop runs as long as `cx` is less than 11.

- Exit Condition: `jge end_outer_loop`

- If the counter is greater than or equal to 11, exit the outer loop.

- Increment: `inc cx`

- Increment the outer loop counter (rows) by 1.

- Jump Back: `jmp outer_loop`

- Jump back to the start of the outer loop.

2. Inner Loop:

- Initialization: `mov dx, 1`

- Initialize the inner loop counter (columns) to 1.

- Comparison: `cmp dx, 11`

- Compare the counter with 11. The loop runs as long as `dx` is less than 11.

- Exit Condition: `jge end_inner_loop`

23
- If the counter is greater than or equal to 11, exit the inner loop.

- Increment: `inc dx`

- Increment the inner loop counter (columns) by 1.

- Jump Back: `jmp inner_loop`

- Jump back to the start of the inner loop.

3. Multiplication and Storage:

- Multiplication: `mov ax, cx` and `mul dx`

- Multiply the current row (`cx`) by the current column (`dx`).

- Index Calculation: `mov bx, 10`, `mul bx`, `add ax, dx`, `dec ax`

- Calculate the zero-based index for storing the result in the `result` array.

- Storage: `mov [result + ax], al`

- Store the result of the multiplication in the `result` array at the calculated index.

4. Exiting the Program:

- System Call: `mov eax, 1`, `xor ebx, ebx`, `int 0x80`

- Perform a system call to exit the program with exit code 0.

Task 5.1:
Examine and explain the methods for data transfer between the CPU and memory in
assembly language. Provide examples of relevant instructions used.

Methods for Data Transfer


1. Direct Memory Access (DMA):

24
- Description: This method allows peripherals to access the memory directly, bypassing the
CPU. It's used for high-speed data transfer, such as disk drives or network interfaces.

- Example: The CPU sets up the DMA controller to handle the data transfer and then goes
into a wait state or continues executing other instructions.

2. Programmed I/O:

- Description: In this method, the CPU is responsible for data transfer between memory and
peripherals. The CPU reads from or writes to memory one word at a time.

- Example: When transferring data from memory to an I/O device, the CPU executes
instructions to read data from memory and write it to the device.

3. Memory-Mapped I/O:

- Description: Peripherals are assigned specific memory addresses. The CPU uses standard
memory instructions to transfer data between memory and these addresses.

- Example: The CPU can read from or write to a peripheral by accessing its assigned
memory address.

Relevant Instructions in Assembly Language.


1. MOV Instruction:

- Description: The MOV instruction is used to transfer data between registers, from a
memory location to a register, from a register to a memory location, or between two memory
locations.

2. PUSH and POP Instructions:

- Description: These instructions are used to transfer data between registers and the stack.

3. LODS, STOS, MOVS Instructions:

- Description: These string manipulation instructions are used for block data transfer.

4. IN and OUT Instructions:

25
- Description: These instructions are used to transfer data between an I/O port and the CPU.

Conclusion.
Data transfer between the CPU and memory is a crucial aspect of assembly language
programming. Various methods, such as direct memory access, programmed I/O, and
memory-mapped I/O, facilitate efficient data transfer.

Task 5.2
: Develop an assembly program that transfers a block of data from one memory location to
another. Include a detailed explanation of the program logic and its execution.

Assembly Language Program.


```assembly

section .data

source db 'Hello, world!' ; Source data to be transferred

length equ $ - source ; Calculate the length of the source data

section .bss

dest resb 13 ; Reserve 13 bytes for the destination data

section .text

global _start

_start:

; Initialize source and destination pointers

mov esi, source ; ESI points to the start of the source data

mov edi, dest ; EDI points to the start of the destination data

mov ecx, length ; ECX holds the number of bytes to transfer

; Loop to transfer data byte by byte

transfer_loop:

26
mov al, [esi] ; Load byte from source into AL

mov [edi], al ; Store byte from AL into destination

inc esi ; Increment source pointer

inc edi ; Increment destination pointer

dec ecx ; Decrement counter

jnz transfer_loop ; If ECX is not zero, repeat the loop

; Exit the program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call the kernel to exit

```

Explanation of Program Logic and Execution.


1. Data Section:

- `source db 'Hello, world!'`: Defines the source data as the string "Hello, world!".

- `length equ $ - source`: Calculates the length of the source data, which is 13 bytes.

2. BSS Section:

- `dest resb 13`: Reserves 13 bytes for the destination data, where the source data will be
copied.

3. Text Section:

- This section contains the program logic and execution instructions.

4. Initialization:

27
- `mov esi, source`: Load the address of the source data into the `ESI` register. `ESI` will
serve as the source pointer.

- `mov edi, dest`: Load the address of the destination data into the `EDI` register. `EDI` will
serve as the destination pointer.

- `mov ecx, length`: Load the length of the source data into the `ECX` register. `ECX` will
serve as the loop counter, holding the number of bytes to transfer.

5. Transfer Loop:

- `transfer_loop:`: Label marking the start of the loop.

- `mov al, [esi]`: Load a byte from the source memory location pointed to by `ESI` into the
`AL` register.

- `mov [edi], al`: Store the byte from the `AL` register into the destination memory location
pointed to by `EDI`.

- `inc esi`: Increment the source pointer (`ESI`) to point to the next byte in the source data.

- `inc edi`: Increment the destination pointer (`EDI`) to point to the next byte in the
destination data.

- `dec ecx`: Decrement the loop counter (`ECX`).

- `jnz transfer_loop`: If the loop counter (`ECX`) is not zero, jump back to the
`transfer_loop` label to repeat the loop. This ensures that the loop continues until all bytes are
transferred.

6. Exit the Program:

- `mov eax, 1`: Prepare the system call number for exiting the program.

- `xor ebx, ebx`: Set the exit code to 0.

- `int 0x80`: Make the system call to exit the program.

28
Task 6.1:
Research and describe the concept of interrupts in assembly language, emphasizing their role
and importance in system operations.

Concept of Interrupts in Assembly Language.


Interrupts are signals to the processor emitted by hardware or software indicating an event
that needs immediate attention. They temporarily halt the execution of the current program
and allow the processor to execute a special function called an interrupt handler or
interrupt service routine (ISR). Once the ISR is executed, the processor resumes the
execution of the original program from where it left off.

Role and Importance in System Operation.


1. Real-Time Response:

- Description: Interrupts allow a system to respond immediately to critical events, such as


input from peripherals (keyboard, mouse), hardware malfunctions, or other urgent processes.

- Importance: They ensure timely processing, crucial in real-time systems where delays can
lead to system failures or data loss.

2. Efficient CPU Utilization:

- Description: Instead of continuously polling devices to check their status (polling


method), the CPU can continue executing other tasks and only handle the device when an
interrupt is received.

- Importance: This improves CPU efficiency by reducing idle times and allowing
multitasking.

3. Prioritization:

- Description: Interrupts can be prioritized. Critical tasks can preempt less important ones,
allowing the system to handle high-priority tasks immediately.

29
- Importance: This ensures that crucial tasks are handled first, enhancing system stability
and performance.

4. System Stability:

- Description: By using interrupts, systems can handle unexpected events or errors


gracefully.

- Importance: This contributes to the overall reliability and robustness of the system.

Types of Interrupts.
1. Hardware Interrupts:

- Description: Generated by hardware devices (e.g., keyboard, mouse, network card) to


signal that they need attention.

- Example: A keyboard interrupt is generated when a key is pressed.

2. Software Interrupts:

- Description: Generated by software instructions, often used to request system services.

- Example: INT 0x80 in Linux is used to invoke system calls.

3. Exceptions:

- Description: Generated by the CPU to signal error conditions or special instructions (e.g.,
division by zero, invalid opcode).

- Example: Divide-by-zero exception.

Example of an Interrupt in Assembly Language.


Here’s an example of a simple assembly language program that demonstrates the use of a
software interrupt to print a message to the screen using a system call in Linux:

30
```assembly

section .data

msg db 'Hello, world!', 0xA ; Message to be printed

len equ $ - msg ; Length of the message

section .text

global _start

_start:

; Write message to stdout

mov eax, 4 ; System call number (sys_write)

mov ebx, 1 ; File descriptor (stdout)

mov ecx, msg ; Pointer to the message

mov edx, len ; Length of the message

int 0x80 ; Call kernel

; Exit program

mov eax, 1 ; System call number (sys_exit)

xor ebx, ebx ; Exit code 0

int 0x80 ; Call kernel to exit

```

Explanation.
1. Message Data Section:

31
- `msg db 'Hello, world!', 0xA`: Defines the message to be printed, ending with a newline
character.

- `len equ $ - msg`: Calculates the length of the message.

2. Text Section:

- The `_start` label marks the beginning of the program.

3. System Call for Writing:

- `mov eax, 4`: Move the system call number for `sys_write` into the `EAX` register.

- `mov ebx, 1`: Move the file descriptor for `stdout` (1) into the `EBX` register.

- `mov ecx, msg`: Move the pointer to the message into the `ECX` register.

- `mov edx, len`: Move the length of the message into the `EDX` register.

- `int 0x80`: Trigger the software interrupt to call the kernel and execute the `sys_write`
system call.

4. System Call for Exiting:

- `mov eax, 1`: Move the system call number for `sys_exit` into the `EAX` register.

- `xor ebx, ebx`: Clear the `EBX` register to set the exit code to 0.

- `int 0x80`: Trigger the software interrupt to call the kernel and exit the program.

Task 6.2:
Write an assembly program that implements a user-defined ISR to handle a keyboard
interrupt. Provide comprehensive comments and documentation to explain each part of your
code.

Assembly Language Program.


```assembly

32
section .data

msg db 'Key pressed: $' ; Message to display when a key is pressed

new_isr dd 0 ; Address of the new ISR

old_isr dd 0 ; Address of the old ISR

section .bss

key resb 1 ; Reserve a byte for storing the pressed key

section .text

global _start

_start:

; Store the old ISR address for interrupt 0x09 (keyboard)

mov ah, 0x35

mov al, 0x09

int 0x21

mov word [old_isr], bx

mov word [old_isr + 2], es

; Set the new ISR address for interrupt 0x09

lea dx, [new_isr]

mov ax, seg new_isr

mov ds, ax

mov ah, 0x25

mov al, 0x09

int 0x21

; Stay in an infinite loop to keep the program running

hang:

33
jmp hang

; New ISR to handle keyboard interrupt

new_isr:

pusha ; Save all general-purpose registers

in al, 0x60 ; Read the scan code from the keyboard controller

mov [key], al ; Store the scan code

out 0x20, al ; Send End of Interrupt (EOI) signal to the PIC

mov ah, 0x09 ; DOS service to display a string

lea dx, [msg]

int 0x21 ; Call DOS interrupt

popa ; Restore all general-purpose registers

jmp far [old_isr] ; Jump to the original ISR

segment .data

msg db 'Key pressed: $'

segment .bss

key resb 1

segment .text

global _start

_start:

; Save the current ISR for interrupt 0x09

mov ax, 0x3509

int 0x21

mov word [old_isr], bx

mov word [old_isr+2], es

34
; Set the new ISR for interrupt 0x09

mov ax, seg new_isr

mov ds, ax

lea dx, [new_isr]

mov ax, 0x2509

int 0x21

; Loop indefinitely

jmp $

new_isr:

pusha

in al, 0x60

mov [key], al

mov ah, 0x09

lea dx, [msg]

int 0x21

popa

jmp far [old_isr]

```

Task 7.1:
Develop a complex assembly program that integrates concepts such as arithmetic operations,
loops, data transfer, and interrupts. Examples include a basic calculator, an LED control
system, or a simple game.

35
Project: Number Guessing Game in Assembly Language.

Assembly Language Program.


```assembly

section .data

prompt db 'Guess the number (1-100): $'

high_msg db 'Too high! Try again.$', 10

low_msg db 'Too low! Try again.$', 10

correct_msg db 'Congratulations! You guessed it!$'

newline db 10, 0

seed dw 1234

section .bss

user_guess resb 1

target_num resb 1

section .text

global _start

_start:

; Initialize seed for random number generation

mov ax, [seed]

out 0x70, al

; Generate target number (1-100)

call generate_random

mov [target_num], al

main_loop:

; Display prompt

36
mov ah, 0x09

lea dx, [prompt]

int 0x21

; Read user's guess

call read_number

mov [user_guess], al

; Compare guess with target number

mov al, [user_guess]

cmp al, [target_num]

je correct_guess

ja too_high

jb too_low

too_high:

; Display "Too high" message

mov ah, 0x09

lea dx, [high_msg]

int 0x21

jmp main_loop

too_low:

; Display "Too low" message

mov ah, 0x09

lea dx, [low_msg]

int 0x21

37
jmp main_loop

correct_guess:

; Display "Congratulations" message

mov ah, 0x09

lea dx, [correct_msg]

int 0x21

; Exit program

call exit_program

generate_random:

; Generate a random number between 1 and 100

mov ah, 0x00

int 0x1A

mov dx, 100

mul dx

div dx

inc dx

mov al, dl

ret

read_number:

mov ah, 0x01 ; BIOS interrupt to read character

int 0x21 ; Read character

38
sub al, '0' ; Convert ASCII to numeric

ret

exit_program:

; Exit program

mov eax, 1

xor ebx, ebx

int 0x80

```

Explanation of the Program Logic and Execution.

1. Data Section:

- `prompt db 'Guess the number (1-100): $'`: Prompt message for user input.

- `high_msg db 'Too high! Try again.$', 10`: Message for when the guess is too high.

- `low_msg db 'Too low! Try again.$', 10`: Message for when the guess is too low.

- `correct_msg db 'Congratulations! You guessed it!$'`: Message for when the guess is
correct.

- `newline db 10, 0`: Newline character.

- `seed dw 1234`: Seed for random number generation.

2. BSS Section:

- `user_guess resb 1`: Storage for the user's guess.

- `target_num resb 1`: Storage for the target number.

3. Text Section:

39
- Initialization:

- `mov ax, [seed]`, `out 0x70, al`: Initialize the seed for random number generation.

- Generate Target Number:

- `call generate_random`: Generate a random number between 1 and 100.

- `mov [target_num], al`: Store the target number.

- Main Loop:

- Display Prompt:

- `mov ah, 0x09`, `lea dx, [prompt]`, `int 0x21`: Display the prompt message for user
input.

- Read User's Guess:

- `call read_number`: Call the subroutine to read the user's guess.

- `mov [user_guess], al`: Store the user's guess.

- Compare Guess with Target Number:

- `cmp al, [target_num]`: Compare the user's guess with the target number.

- `je correct_guess`: If the guess is equal to the target number, jump to `correct_guess`.

- `ja too_high`: If the guess is greater than the target number, jump to `too_high`.

- `jb too_low`: If the guess is less than the target number, jump to `too_low`.

- Feedback Messages:

- Too High:

- `mov ah, 0x09`, `lea dx, [high_msg]`, `int 0x21`: Display the too high message.

- `jmp main_loop`: Return to the main loop.

- Too Low:

- `mov ah, 0x09`, `lea dx, [low_msg]`, `int 0x21`: Display the too low message.

- `jmp main_loop`: Return to the main loop.

- Correct Guess:

40
- `mov ah, 0x09`, `lea dx, [correct_msg]`, `int 0x21`: Display the congratulations
message.

- Exit Program:

- `call exit_program`: Exit the program.

4. Subroutines:

- generate_random: Generates a random number between 1 and 100.

- read_number: Reads a character from the keyboard and converts it from ASCII to
numeric.

- exit_program: Cleanly exits the program.

Task 7.2
: Document your project in detail, including program logic, flowcharts, and a report on
challenges faced and how they were addressed.

Project: Guess the Number Game in Assembly Language.

Program Logic.

1. Initialization:

- Generate a random number between 1 and 100 (for simplicity, we'll use a hard-coded
number).

- Prompt the user to guess the number.

2. User Input and Validation:

- Read the user's guess.

- Compare the guess to the target number.

41
- Provide feedback (too high, too low, correct).

3. Game Loop:

- Repeat the process until the user guesses the correct number.

4. Exit the Program:

- Cleanly exit the program.

Assembly Language Progra.


```assembly

section .data

target db 50 ; Hard-coded target number (between 1 and 100)

prompt db 'Guess the number (1-100): $'

high_msg db 'Too high! Try again.$'

low_msg db 'Too low! Try again.$'

correct_msg db 'Congratulations! You guessed it!$'

guess db 0 ; Storage for the user's guess

section .bss

section .text

global _start

_start:

; Display prompt

mov ah, 0x09

lea dx, [prompt]

42
int 0x21

guess_loop:

; Read user's guess

call read_number

mov [guess], al

; Compare guess with target

mov al, [guess]

cmp al, [target]

je correct_guess

; Check if the guess is too high or too low

jl too_low

too_high:

; Display "Too high" message

mov ah, 0x09

lea dx, [high_msg]

int 0x21

jmp guess_loop

too_low:

; Display "Too low" message

43
mov ah, 0x09

lea dx, [low_msg]

int 0x21

jmp guess_loop

correct_guess:

; Display "Congratulations" message

mov ah, 0x09

lea dx, [correct_msg]

int 0x21

; Exit program

mov eax, 1

xor ebx, ebx

int 0x80

read_number:

mov ah, 0x01 ; BIOS interrupt to read character

int 0x21 ; Read character

sub al, '0' ; Convert ASCII to numeric

ret

```

Explanation of the Program Logic and Execution.

1. Data Section:

- `target db 50`: The target number for the game (hard-coded for simplicity).

44
- `prompt db 'Guess the number (1-100): $'`: Prompt message for the user's guess.

- `high_msg db 'Too high! Try again.$'`: Message for when the guess is too high.

- `low_msg db 'Too low! Try again.$'`: Message for when the guess is too low.

- `correct_msg db 'Congratulations! You guessed it!$'`: Message for when the guess is
correct.

- `guess db 0`: Storage for the user's guess.

2. Text Section:

- Initialization:

- `mov ah, 0x09`, `lea dx, [prompt]`, `int 0x21`: Display the prompt message for the user's
guess.

- Guess Loop:

- Reading User's Guess:

- `call read_number`: Call the subroutine to read the user's guess.

- `mov [guess], al`: Store the user's guess.

- Comparing Guess with Target:

- `cmp al, [target]`: Compare the user's guess with the target number.

- `je correct_guess`: If the guess is equal to the target, jump to the correct guess message.

- `jl too_low`: If the guess is less than the target, jump to the too low message.

- Too High:

- `mov ah, 0x09`, `lea dx, [high_msg]`, `int 0x21`: Display the too high message.

- `jmp guess_loop`: Jump back to the guess loop to prompt the user again.

- Too Low:

- `mov ah, 0x09`, `lea dx, [low_msg]`, `int 0x21`: Display the too low message.

- `jmp guess_loop`: Jump back to the guess loop to prompt the user again.

- Correct Guess:

45
- `mov ah, 0x09`, `lea dx, [correct_msg]`, `int 0x21`: Display the correct guess message.

- Exit Program:

- `mov eax, 1`, `xor ebx, ebx`, `int 0x80`: Exit the program using a system call.

3. Subroutines:

- read_number: Reads a character from the keyboard and converts it from ASCII to
numeric.

- `mov ah, 0x01`, `int 0x21`: BIOS interrupt to read a character.

- `sub al, '0'`: Convert ASCII to numeric.

Flowchart.
Here's a flowchart to visualize the program logic:

```plaintext

+ +

| Start |

+ +

+ +

| Display Prompt |

| Guess the number |

+ +

+ +

| Read Guess |

46
+ +

+ +

| Compare Guess with |

| Target |

+ +

+ + +

| | |

lt eq gt

| | |

v v v

+ + + +

| Display "Too | | Display "Correct" |

| Low" Message | + -------------------- +

+ + |

| v

+ >+ +

| Exit Program |

+ +

```

Challenges Faced and Solutions.


1. User Input Handling:

47
- Challenge: Ensuring valid numeric input from the user.

- Solution: Reading single characters and converting them from ASCII to numeric values,
limiting the input to digits only.

2. Game Loop Implementation:

- Challenge: Continuously prompting the user until the correct guess is made.

- Solution: Using a loop structure with conditional jumps (`je`, `jl`, `jmp`) to control the
flow based on the user's input and comparison results.

3. Feedback Display:

- Challenge: Providing real-time feedback to the user based on their guess (too high, too
low, correct).

- Solution: Displaying appropriate messages using BIOS interrupts and branching to the
correct parts of the program based on the comparison results.

references

Irvine, K. R. (2010). Assembly Language for x86 Processors. Pearson.

Bartlett, J. (2004). Programming from the Ground Up. Bartlett Publishing.

Hyde, R. (2010). The Art of Assembly Language. No Starch Press.

Kusswurm, D. (2014). Modern X86 Assembly Language Programming: 32-bit, 64-bit,


SSE, and AVX. Apress.

Smith, S. (2020). Programming with 64-Bit ARM Assembly Language: Single Board
Computer Development for Raspberry Pi and Mobile Devices. Apress.

Smith, B. (2020). Raspberry Pi Assembly Language RASPBIAN Beginners. BSB


Publications.

48

You might also like