Showing posts with label MP. Show all posts
Showing posts with label MP. Show all posts

Wednesday, 12 March 2025

Programs in Assembly Language

Addition of Two Numbers

section .data

    num1 dd 10      ; First number (32-bit)

    num2 dd 20      ; Second number (32-bit)

    result dd 0     ; Store the result (32-bit)


section .text

    global _start


_start:

    mov eax, [num1] ; Load num1 into EAX

    add eax, [num2] ; Add num2 to EAX

    mov [result], eax ; Store result in memory


    ; Exit program

    mov eax, 1      ; sys_exit syscall

    xor ebx, ebx    ; Exit code 0

    int 0x80        ; Call kernel

Explanation

  1. Data Section (.data)

    • num1 and num2 store the two numbers to be added.
    • result is reserved for storing the sum.
  2. Code Section (.text)

    • Load num1 into the EAX register.
    • Add num2 to EAX using the ADD instruction.
    • Store the result back into memory (result).
    • Exit the program using a system call.

Subtraction of Two Numbers in Assembly Language (x86 - NASM)

In assembly language, subtraction is performed using the SUB instruction. Below is a simple x86 assembly program that subtracts two numbers and stores the result.


Code: Subtraction of Two Numbers (x86 Assembly - NASM)

section .data
num1 dd 30 ; First number (32-bit) num2 dd 10 ; Second number (32-bit) result dd 0 ; To store the subtraction result section .text global _start _start: mov eax, [num1] ; Load num1 into EAX sub eax, [num2] ; Subtract num2 from EAX mov [result], eax ; Store the result in memory ; Exit the program mov eax, 1 ; sys_exit system call xor ebx, ebx ; Exit code 0 int 0x80 ; Call kernel

Explanation

  1. Data Section (.data)

    • num1 stores the first number (30).
    • num2 stores the second number (10).
    • result is reserved for storing the result of num1 - num2.
  2. Code Section (.text)

    • Load num1 into EAX register.
    • Subtract num2 from EAX using SUB instruction.
    • Store the result in memory (result).
    • Exit the program using a system call.

Addition of two 8 bit BCD Number
Algorithm

step 1. Initialize data segment.

Step 2. Initialize MSB counter with 0.

step 3. Load first BCD number in AL.

step 4. Add second BCD number with AL.

step 5. Adjust result to BCD.

step 6. If result > 8 bit then goto step 7 else 8.

step 7. Increment MSB counter by 1.

step 8. Store result.

step 9. End

Program

.model small

data

num1 db 84H; First 8 bit BCD Number

num2 db 28H; Second 8 bit BCD Number

res_lsb db 0 ; Variable to store LSB of result

res_msb db 0 .code ;Variable to store MSB of result

mov ax, @data ; Initialize data segment

mov ds, ax

mov al, num1 ; Load first BCD number in AL

add al, num2 ; Add second BCD number with first

daa ; Adjust result to correct BCD

jnc dn; if result > 8 bit if no go to dn

inc res_msb ; else increment MSB result counter

dn: mov res_lsb, al

ends

end


ALP to check a given number is odd or even.

🔧 Program Description:

This program checks the least significant bit (LSB) of the number.

  • If LSB is 0, the number is even.

  • If LSB is 1, the number is odd.

.MODEL SMALL
.STACK 100H
.DATA
    number DB 7         ; You can change this number as needed
    msg_even DB 'Number is Even$', 0
    msg_odd  DB 'Number is Odd$', 0

.CODE
MAIN PROC
    MOV AX, @DATA       ; Initialize data segment
    MOV DS, AX

    MOV AL, number      ; Load the number into AL
    TEST AL, 1          ; Perform bitwise AND with 1 to check LSB

    JZ EVEN             ; If zero, it's even
    LEA DX, msg_odd     ; Else, it's odd
    JMP DISPLAY

EVEN:
    LEA DX, msg_even

DISPLAY:
    MOV AH, 09H         ; DOS interrupt to print string
    INT 21H

    MOV AH, 4CH         ; Exit program
    INT 21H
MAIN ENDP
END MAIN

 Sample Output:

If number DB 7, it prints:

Number is Odd

If number DB 4, it prints:

Number is Even
ALP to find the length of string and concatenate two strings

Here’s a neat 8086 Assembly Language Program (ALP) that does two things:

  1. ✅ Finds the length of a string

  2. ✅ Concatenates two strings

💾 Assumptions:

  • Strings are stored in .DATA segment.

  • Each string is terminated with $, as expected by DOS for display.

  • We will manually concatenate without using any built-in function.

.MODEL SMALL
.STACK 100H
.DATA
    str1 DB 'Hello, ', '$'
    str2 DB 'World!', '$'
    lenMsg DB 'Length of str1: $'
    newline DB 13, 10, '$'
    result DB 50 DUP('$') ; Space for concatenated result

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX
    MOV ES, AX

    ;------------- Find Length of str1 -------------
    LEA SI, str1       ; Point SI to str1
    MOV CX, 0

FIND_LEN:
    MOV AL, [SI]
    CMP AL, '$'
    JE  SHOW_LEN
    INC CX
    INC SI
    JMP FIND_LEN

SHOW_LEN:
    ; Display "Length of str1: "
    LEA DX, lenMsg
    MOV AH, 09H
    INT 21H

    ; Convert CX to ASCII and display it
    MOV AX, CX
    CALL PRINT_NUM

    ; Print newline
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    ;------------- Concatenate str1 and str2 into result -------------

    LEA SI, str1
    LEA DI, result

COPY_STR1:
    MOV AL, [SI]
    CMP AL, '$'
    JE  COPY_STR2
    MOV [DI], AL
    INC SI
    INC DI
    JMP COPY_STR1

COPY_STR2:
    LEA SI, str2

COPY_LOOP2:
    MOV AL, [SI]
    CMP AL, '$'
    JE  DONE_CONCAT
    MOV [DI], AL
    INC SI
    INC DI
    JMP COPY_LOOP2

DONE_CONCAT:
    MOV BYTE PTR [DI], '$'   ; Terminate with $

    ; Display the concatenated result
    LEA DX, result
    MOV AH, 09H
    INT 21H

    ; Exit program
    MOV AH, 4CH
    INT 21H

MAIN ENDP

;--------- Print number in AX ---------
; AX contains number to print
PRINT_NUM PROC
    PUSH AX
    PUSH BX
    PUSH CX
    PUSH DX

    XOR CX, CX
    MOV BX, 10

REPEAT_DIV:
    XOR DX, DX
    DIV BX
    PUSH DX
    INC CX
    CMP AX, 0
    JNE REPEAT_DIV

PRINT_LOOP:
    POP DX
    ADD DL, 30H
    MOV AH, 02H
    INT 21H
    LOOP PRINT_LOOP

    POP DX
    POP CX
    POP BX
    POP AX
    RET
PRINT_NUM ENDP

END MAIN

🧪 Sample Output:

Length of str1: 7 Hello, World!
ALP to find smallest and largest number from array of numbers.

💡 Logic Overview

  • Loop through the array

  • Compare each element with min and max

  • Replace min if smaller, replace max if larger

.MODEL SMALL
.STACK 100H
.DATA
    array DB 25, 10, 45, 3, 89, 2, 77, 15, 66
    size  DB 9          ; Total number of elements
    minVal DB ?
    maxVal DB ?
    msgMin DB 'Smallest number: $'
    msgMax DB 'Largest number: $'
    newline DB 13, 10, '$'

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    ; Initialize registers
    MOV CX, size        ; Load size of array
    MOV SI, 0           ; Index to array
    MOV AL, array[SI]   ; Load first element
    MOV minVal, AL
    MOV maxVal, AL
    INC SI              ; Start from second element
    DEC CX              ; Already considered one

FIND_LOOP:
    MOV AL, array[SI]

    ; Compare with min
    CMP AL, minVal
    JAE SKIP_MIN
    MOV minVal, AL

SKIP_MIN:
    ; Compare with max
    CMP AL, maxVal
    JBE SKIP_MAX
    MOV maxVal, AL

SKIP_MAX:
    INC SI
    LOOP FIND_LOOP

    ;--------- Display Minimum ---------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    LEA DX, msgMin
    MOV AH, 09H
    INT 21H

    MOV AL, minVal
    CALL PRINT_NUM

    ;--------- Display Maximum ---------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    LEA DX, msgMax
    MOV AH, 09H
    INT 21H

    MOV AL, maxVal
    CALL PRINT_NUM

    ; Exit program
    MOV AH, 4CH
    INT 21H
MAIN ENDP

;--------- Subroutine to Print 8-bit Number in AL ---------
PRINT_NUM PROC
    ; Convert AL to decimal and print
    ; AL contains the number
    MOV AH, 0
    MOV BL, 10
    XOR CX, CX

CONVERT_LOOP:
    XOR AH, AH
    DIV BL
    PUSH AX
    INC CX
    MOV AL, AH
    MOV AH, 0
    CMP AL, 0
    JNZ CONVERT_LOOP
    POP AX

PRINT_LOOP:
    POP DX
    ADD DL, 30H
    MOV AH, 02H
    INT 21H
    LOOP PRINT_LOOP
    RET
PRINT_NUM ENDP

END MAIN

🧪 Sample Output

Smallest number: 2 Largest number: 89
ALP to perform block transfer operation.

A block transfer is copying a block of data (like an array or string) from one memory location to another.

We use:

  • SI (Source Index) for source

  • DI (Destination Index) for destination

  • CX to store count (number of bytes to transfer)

  • MOVSB to move each byte

.MODEL SMALL
.STACK 100H
.DATA
    source  DB 10H, 20H, 30H, 40H, 50H  ; 5 bytes of data
    dest    DB 5 DUP(0)                ; Empty destination buffer

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX
    MOV ES, AX                        ; Same segment for destination

    LEA SI, source                    ; SI points to source
    LEA DI, dest                      ; DI points to destination
    MOV CX, 5                         ; Number of bytes to transfer

CLD                                  ; Clear direction flag (forward)

REP MOVSB                            ; Repeat moving byte from [SI] to [DI] CX times

    ; Exit Program
    MOV AH, 4CH
    INT 21H
MAIN ENDP
END MAIN

🧠 Explanation:

InstructionDescription
MOV AX, @DATALoad address of data segment
MOV DS, AXInitialize DS
MOV ES, AXSame segment used for both source and destination
LEA SI, sourceSI points to start of source block
LEA DI, destDI points to destination block
MOV CX, 5We want to move 5 bytes
CLDClear Direction Flag (moves forward in memory)
REP MOVSBRepeats MOVSB CX times, copying byte from [SI] to [DI]

ALP to perform arithmetic operations on given numbers using procedure.

🔧 What it does:

  • Operates on two predefined numbers

  • Calls separate procedures for each operation

  • Displays results using DOS interrupt

.MODEL SMALL
.STACK 100H
.DATA
    num1 DB 20
    num2 DB 5
    msgAdd DB 'Addition: $'
    msgSub DB 'Subtraction: $'
    msgMul DB 'Multiplication: $'
    msgDiv DB 'Division: $'
    newline DB 13, 10, '$'

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    ; ---------- Addition ----------
    LEA DX, msgAdd
    MOV AH, 09H
    INT 21H

    CALL ADD_PROC
    CALL PRINT_NUM

    ; ---------- Subtraction ----------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    LEA DX, msgSub
    MOV AH, 09H
    INT 21H

    CALL SUB_PROC
    CALL PRINT_NUM

    ; ---------- Multiplication ----------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    LEA DX, msgMul
    MOV AH, 09H
    INT 21H

    CALL MUL_PROC
    CALL PRINT_NUM

    ; ---------- Division ----------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    LEA DX, msgDiv
    MOV AH, 09H
    INT 21H

    CALL DIV_PROC
    CALL PRINT_NUM

    ; Exit program
    MOV AH, 4CH
    INT 21H
MAIN ENDP

; Adds num1 and num2, result in AL
ADD_PROC PROC
    MOV AL, num1
    ADD AL, num2
    RET
ADD_PROC ENDP

; Subtracts num2 from num1, result in AL
SUB_PROC PROC
    MOV AL, num1
    SUB AL, num2
    RET
SUB_PROC ENDP

; Multiplies num1 * num2, result in AL
MUL_PROC PROC
    MOV AL, num1
    MOV BL, num2
    MUL BL           ; AL = AL * BL
    RET
MUL_PROC ENDP

; Divides num1 / num2, quotient in AL
DIV_PROC PROC
    MOV AL, num1
    MOV AH, 0
    MOV BL, num2
    DIV BL           ; AL = quotient
    RET
DIV_PROC ENDP

Helper Procedure to print Result
; Print 8-bit number in AL
PRINT_NUM PROC
    PUSH AX
    PUSH BX
    PUSH CX
    PUSH DX

    XOR CX, CX
    MOV BX, 10

    ; Convert to decimal digits
    PRINT_LOOP:
        XOR DX, DX
        DIV BX
        PUSH DX
        INC CX
        CMP AX, 0
        JNZ PRINT_LOOP

    ; Print digits
    PRINT_DIGITS:
        POP DX
        ADD DL, 30H
        MOV AH, 02H
        INT 21H
        LOOP PRINT_DIGITS

    POP DX
    POP CX
    POP BX
    POP AX
    RET
PRINT_NUM ENDP

✅ Sample Output:


Addition: 25 Subtraction: 15 Multiplication: 100 Division: 4
ALP to perform addition and subtraction of two given numbers.

💡 Program Description

  • Operates on two 8-bit numbers (num1 and num2)

  • Performs:

    • Addition: num1 + num2

    • Subtraction: num1 - num2

  • Displays the results using DOS interrupts

.MODEL SMALL
.STACK 100H
.DATA
    num1 DB 25
    num2 DB 10
    msgAdd DB 'Addition: $'
    msgSub DB 'Subtraction: $'
    newline DB 13, 10, '$'

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    ; ----------- Addition ------------
    LEA DX, msgAdd
    MOV AH, 09H
    INT 21H

    MOV AL, num1
    ADD AL, num2
    CALL PRINT_NUM

    ; ---------- New Line -------------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    ; ----------- Subtraction ---------
    LEA DX, msgSub
    MOV AH, 09H
    INT 21H

    MOV AL, num1
    SUB AL, num2
    CALL PRINT_NUM

    ; ----------- Exit ----------------
    MOV AH, 4CH
    INT 21H
MAIN ENDP

; ------- Procedure to Print Number in AL -------
PRINT_NUM PROC
    PUSH AX
    PUSH BX
    PUSH CX
    PUSH DX

    XOR CX, CX
    MOV BL, 10

    ; Convert AL to decimal digits
    NEXT_DIGIT:
        XOR AH, AH
        DIV BL
        PUSH AX
        INC CX
        CMP AL, 0
        JNZ NEXT_DIGIT

    ; Print digits
    PRINT_LOOP:
        POP DX
        AND DL, 0FH
        ADD DL, 30H
        MOV AH, 02H
        INT 21H
        LOOP PRINT_LOOP

    POP DX
    POP CX
    POP BX
    POP AX
    RET
PRINT_NUM ENDP

END MAIN

🧪 Sample Output

Addition: 35 Subtraction: 15

ALP to arrange numbers in an array in ascending or descending order.

✅ Features:

  • Works on an array of 8-bit numbers

  • Can easily toggle between ascending or descending

  • Uses Bubble Sort (simple and easy for 8086)

.MODEL SMALL
.STACK 100H
.DATA
    array DB 5, 2, 9, 1, 7, 3
    size  DB 6                ; Number of elements in array

    newline DB 13, 10, '$'
    msgAsc DB 'Sorted in Ascending Order: $'
    msgDesc DB 'Sorted in Descending Order: $'

.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    ; ------------ Sort Ascending -------------
    LEA DX, msgAsc
    MOV AH, 09H
    INT 21H

    CALL SORT_ASC
    CALL PRINT_ARRAY

    ; ------------ New Line -------------------
    LEA DX, newline
    MOV AH, 09H
    INT 21H

    ; ------------ Sort Descending ------------
    LEA DX, msgDesc
    MOV AH, 09H
    INT 21H

    CALL SORT_DESC
    CALL PRINT_ARRAY

    ; ------------ Exit -----------------------
    MOV AH, 4CH
    INT 21H
MAIN ENDP

; ------------ Sort in Ascending Order ------------
SORT_ASC PROC
    MOV CX, size
    DEC CX              ; Outer loop count = size - 1

OUTER_ASC:
    MOV SI, 0
    MOV BX, CX          ; Inner loop count

INNER_ASC:
    MOV AL, array[SI]
    MOV DL, array[SI+1]
    CMP AL, DL
    JBE NO_SWAP_ASC

    ; Swap AL and DL
    MOV array[SI], DL
    MOV array[SI+1], AL

NO_SWAP_ASC:
    INC SI
    DEC BX
    JNZ INNER_ASC
    DEC CX
    JNZ OUTER_ASC
    RET
SORT_ASC ENDP

; ------------ Sort in Descending Order ------------
SORT_DESC PROC
    MOV CX, size
    DEC CX              ; Outer loop count = size - 1

OUTER_DESC:
    MOV SI, 0
    MOV BX, CX          ; Inner loop count

INNER_DESC:
    MOV AL, array[SI]
    MOV DL, array[SI+1]
    CMP AL, DL
    JAE NO_SWAP_DESC

    ; Swap AL and DL
    MOV array[SI], DL
    MOV array[SI+1], AL

NO_SWAP_DESC:
    INC SI
    DEC BX
    JNZ INNER_DESC
    DEC CX
    JNZ OUTER_DESC
    RET
SORT_DESC ENDP

; ------------ Print Array -------------
PRINT_ARRAY PROC
    MOV CX, size
    MOV SI, 0

PRINT_LOOP:
    MOV AL, array[SI]
    CALL PRINT_NUM

    ; Print space
    MOV DL, ' '
    MOV AH, 02H
    INT 21H

    INC SI
    LOOP PRINT_LOOP

    RET
PRINT_ARRAY ENDP

; ------------ Print Number in AL -------------
PRINT_NUM PROC
    PUSH AX
    PUSH BX
    PUSH CX
    PUSH DX

    XOR CX, CX
    MOV BL, 10

    ; Convert to decimal
    CONVERT:
        XOR AH, AH
        DIV BL
        PUSH AX
        INC CX
        CMP AL, 0
        JNZ CONVERT

    ; Print digits
    PRINT_DIGITS:
        POP DX
        AND DL, 0FH
        ADD DL, 30H
        MOV AH, 02H
        INT 21H
        LOOP PRINT_DIGITS

    POP DX
    POP CX
    POP BX
    POP AX
    RET
PRINT_NUM ENDP

END MAIN

🧪 Sample Output:


Sorted in Ascending Order: 1 2 3 5 7 9 Sorted in Descending Order: 9 7 5 3 2 1

Programming using Assembler

In assembly language, a block structure refers to the way instructions, data, and control flow constructs are grouped together logically within a program. While assembly language does not have high-level constructs like loops and functions in the same way as languages like C or Python, programmers use labels, directives, and indentation to create structured and readable code.


Key Elements of Block Structure in Assembly

  1. Data Section
    Defines variables, constants, and memory storage.


    section .data msg db "Hello, World!", 0
  2. Code Section
    Contains the actual instructions executed by the CPU.


    section .text global _start _start: mov eax, 1 ; System call number (sys_exit) xor ebx, ebx ; Exit code 0 int 0x80 ; Invoke system call
  3. Procedures (Subroutines/Functions)
    Blocks of reusable code that can be called from different places.


    my_function: push ebp mov ebp, esp ; Function body mov esp, ebp pop ebp ret
  4. Loops and Conditional Blocks

    • Loops can be implemented using jmp, loop, or cmp followed by conditional jumps.

    mov ecx, 5 ; Counter for loop loop_start: dec ecx jnz loop_start ; Jump if ecx is not zero
    • Conditional blocks use comparison and jump instructions:

    cmp eax, ebx je equal_label ; Jump if equal jg greater_label ; Jump if greater jl less_label ; Jump if less
  5. Stack-Based Block Structure

    • Functions or local variables are often managed using the stack.

    push eax call my_function pop eax

Example of a Structured Assembly Program


section .data msg db "Hello, Assembly!", 0 section .bss buffer resb 16 section .text global _start _start: ; Calling function call print_msg ; Exit program mov eax, 1 xor ebx, ebx int 0x80 print_msg: ; Function to print a message mov eax, 4 mov ebx, 1 mov ecx, msg mov edx, 16 int 0x80 ret

Conclusion

While assembly lacks built-in block structures like {} in C, proper use of labels, indentation, and sections can create a clear and structured program. Using functions, loops, and stack-based organization helps in maintaining better readability and modularity in assembly code.

Variables and Constants in Assembly Language

In assembly language, variables and constants are used to store and reference data in memory. Since assembly does not have high-level variable types like in C or Python, variables are simply named memory locations with specific sizes and values.


1. Variables in Assembly Language

A variable is a memory location that holds a value and can be modified during execution.

Defining Variables

Variables are typically defined in the data section (.data) or the uninitialized section (.bss).

Syntax for Declaring Variables

variable_name data_type initial_value

Common Data Types in Assembly

Data TypeSize (Bytes)Description
db (Define Byte)1 ByteStores a single byte (8-bit)
dw (Define Word)2 BytesStores a word (16-bit)
dd (Define Double Word)4 BytesStores a double word (32-bit)
dq (Define Quad Word)8 BytesStores a quad word (64-bit)

Example of Variable Declaration

section .data num1 db 10 ; 8-bit variable storing 10 num2 dw 1000 ; 16-bit variable storing 1000 num3 dd 123456 ; 32-bit variable storing 123456 message db "Hello, World!", 0 ; String (null-terminated)

Accessing and Modifying Variables

To access a variable, you load its address or value into a register:

mov al, [num1] ; Load 8-bit value of num1 into AL register mov ax, [num2] ; Load 16-bit value of num2 into AX register mov eax, [num3] ; Load 32-bit value of num3 into EAX register

To modify a variable:


mov byte [num1], 20 ; Change value of num1 to 20 mov word [num2], 2000 ; Change value of num2 to 2000 mov dword [num3], 999999 ; Change value of num3 to 999999

2. Constants in Assembly Language

A constant is a value that does not change during execution. Unlike variables, constants are assigned at assembly time and cannot be modified.

Defining Constants

Constants are defined using the equ directive or %define (macro-style).

Using equ (Constant Definition)

PI equ 3.1415 ; Defines a constant named PI SIZE equ 10 ; SIZE is now 10

Usage:

mov eax, SIZE ; Load constant value into register

Using %define (Macro-style Constant)


%define MAX_VALUE 100

Usage:


mov ebx, MAX_VALUE ; MAX_VALUE is replaced with 100 at assembly time

3. Differences Between Variables and Constants

FeatureVariableConstant
ValueCan change during executionFixed at assembly time
StorageAllocates memoryNo memory allocated (replaced during assembly)
DefinitionDefined in .data or .bss sectionDefined using equ or %define
UsageRequires memory accessDirect substitution in instructions

4. Example Program Using Variables and Constants

section .data num1 db 10 message db "Hello, Assembly!", 0 section .bss buffer resb 16 ; Reserve 16 bytes of uninitialized memory section .text global _start %define EXIT_CODE 0 ; Constant definition _start: ; Load variable num1 into AL register mov al, [num1] ; Print message mov eax, 4 ; sys_write mov ebx, 1 ; File descriptor (stdout) mov ecx, message ; Pointer to message mov edx, 16 ; Message length int 0x80 ; Call kernel ; Exit program mov eax, 1 ; sys_exit mov ebx, EXIT_CODE ; Use constant int 0x80 ; Call kernel

Conclusion

  • Variables store values in memory and can be modified during execution.
  • Constants are fixed values replaced at assembly time.
  • Variables use directives like db, dw, dd, while constants use equ or %define.

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...