Monday, 24 February 2025

Assembly Language Programming

 Unit 4

Models of 8086 Assembly Language Program

The 8086 microprocessor supports different memory models based on how much memory a program needs. These models determine how code, data, and stack are organized in memory.


1. Types of Memory Models in 8086

The Intel 8086 processor operates in Real Mode, where it can address up to 1MB of memory. Based on how memory is divided, the following models are available:

Memory Model

Code Size

Data Size

Stack Size

Segments Used

Tiny

≤ 64 KB

≤ 64 KB

≤ 64 KB

Single Segment (CS = DS = SS)

Small

≤ 64 KB

≤ 64 KB

≤ 64 KB

Separate CS, DS, SS

Medium

Unlimited

≤ 64 KB

≤ 64 KB

Separate CS, DS, SS

Compact

≤ 64 KB

Unlimited

≤ 64 KB

Separate CS, DS, SS

Large

Unlimited

Unlimited

≤ 64 KB

Separate CS, DS, SS

Huge

Unlimited

Unlimited

Unlimited

Separate CS, DS, SS


2. Explanation of Each Memory Model

a) Tiny Model

  • Entire program (code, data, stack) fits within a single 64 KB segment.
  • CS = DS = SS (single segment).
  • Mostly used for .COM files.

Example:

assembly

.MODEL TINY

.CODE

ORG 100H  ; Required for COM file execution


START:

    MOV AH, 09H

    MOV DX, OFFSET MSG

    INT 21H  ; Print message


    MOV AX, 4C00H

    INT 21H  ; Exit program


MSG DB 'Hello, World!$'


END START


b) Small Model

  • Code, data, and stack have separate segments.
  • Code and data each fit in 64 KB.
  • Used for simple .EXE programs.

Example:

assembly

.MODEL SMALL

.STACK 100H

.DATA

MSG DB 'Hello, 8086!$'


.CODE

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX  ; Initialize data segment


    MOV AH, 09H

    MOV DX, OFFSET MSG

    INT 21H  ; Print message


    MOV AX, 4C00H

    INT 21H  ; Exit program

MAIN ENDP


END MAIN


c) Medium Model

  • Code can exceed 64 KB (multiple code segments).
  • Data is limited to 64 KB.
  • Used for large programs with multiple functions.

Example:

assembly

.MODEL MEDIUM

.STACK 100H

.DATA

MSG DB 'Welcome to Medium Model$'


.CODE

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX


    MOV AH, 09H

    MOV DX, OFFSET MSG

    INT 21H


    MOV AX, 4C00H

    INT 21H

MAIN ENDP


END MAIN


d) Compact Model

  • Multiple data segments but single code segment.
  • Used when data is large but code remains within 64 KB.

Example:

assembly

.MODEL COMPACT

.STACK 100H

.DATA

BUFFER DB 256 DUP('$')  ; Large data buffer


.CODE

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX


    ; Your program logic here


    MOV AX, 4C00H

    INT 21H

MAIN ENDP


END MAIN


e) Large Model

  • Both code and data can exceed 64 KB.
  • Each function and data block may be in different segments.
  • Used for very large programs.

Example:

assembly

.MODEL LARGE

.STACK 100H

.DATA

MSG DB 'Large Model Example$'

 

.CODE

MAIN PROC FAR

    MOV AX, @DATA

    MOV DS, AX


    MOV AH, 09H

    MOV DX, OFFSET MSG

    INT 21H


    MOV AX, 4C00H

    INT 21H

MAIN ENDP


END MAIN


f) Huge Model

  • Multiple code and multiple data segments.
  • Used for handling large arrays beyond 64 KB.
  • Similar to Large Model, but pointers can access full segment addressing.

assembly

.MODEL HUGE

.STACK 100H

.DATA

BIG_ARRAY DW 50000 DUP(0)  ; Huge array


.CODE

MAIN PROC FAR

    MOV AX, @DATA

    MOV DS, AX


    ; Program logic


    MOV AX, 4C00H

    INT 21H

MAIN ENDP


END MAIN


3. Choosing the Right Model

  • Tiny → Small programs, .COM files.
  • Small → Standard programs, fits within 64 KB code & data.
  • Medium → Large programs, multiple functions with a single data segment.
  • CompactLarge data but small code.
  • LargeLarge programs requiring multiple code & data segments.
  • Huge → Needed for very large arrays/structures (more than 64 KB).

4. Summary

  • The 8086 memory model is selected based on code, data, and stack size.
  • Tiny model is for compact programs, small & medium for most applications.
  • Large and huge models handle big programs and massive data structures.
  • Use .MODEL directive in MASM (Microsoft Macro Assembler) to specify the model.

Object Oriented Programming in Python

Unit 4 

Object-Oriented Programming (OOP) in Python

1. What is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects and classes. It helps in structuring complex programs by organizing data (attributes) and behavior (methods) into objects.


2. Key OOP Concepts in Python

OOP Concept

Description

Example

Class

A blueprint for creating objects

class Car:

Object

An instance of a class

my_car = Car()

Encapsulation

Hiding data using private/protected members

self.__speed = 50

Inheritance

One class can inherit properties of another

class SportsCar(Car)

Polymorphism

Different classes can have methods with the same name

def start_engine() in multiple classes

Abstraction

Hiding implementation details from users

from abc import ABC, abstractmethod


3. Creating Classes and Objects

a) Defining a Class

A class is a blueprint for creating objects. It defines attributes and methods.

python

class Car:

    def __init__(self, brand, model, year):

        self.brand = brand

        self.model = model

        self.year = year

 

    def display_info(self):

        return f"{self.year} {self.brand} {self.model}"

b) Creating Objects (Instances)

An object is an instance of a class.

python

car1 = Car("Toyota", "Corolla", 2022)

car2 = Car("Honda", "Civic", 2023)

 

print(car1.display_info())  # Output: 2022 Toyota Corolla

print(car2.display_info())  # Output: 2023 Honda Civic


4. Encapsulation (Data Hiding)

Encapsulation restricts access to certain attributes using private (__) and protected (_) members.

python

class BankAccount:

    def __init__(self, balance):

        self.__balance = balance  # Private variable

 

    def deposit(self, amount):

        self.__balance += amount

 

    def get_balance(self):

        return self.__balance

 

# Creating object

account = BankAccount(1000)

account.deposit(500)

print(account.get_balance())  # Output: 1500

 

# Accessing private variable (will cause an error)

# print(account.__balance)  # AttributeError


5. Inheritance (Code Reusability)

Inheritance allows one class to inherit attributes and methods from another class.

a) Single Inheritance

python

class Animal:

    def sound(self):

        return "Some generic sound"

 

class Dog(Animal):

    def sound(self):  # Method overriding

        return "Bark"

 

dog = Dog()

print(dog.sound())  # Output: Bark

b) Multiple Inheritance

A child class can inherit from multiple parent classes.

python

class A:

    def method_A(self):

        return "Method from Class A"

 

class B:

    def method_B(self):

        return "Method from Class B"

 

class C(A, B):

    pass

 

obj = C()

print(obj.method_A())  # Output: Method from Class A

print(obj.method_B())  # Output: Method from Class B


6. Polymorphism (Different Behavior for the Same Method)

Polymorphism allows different classes to have the same method name with different implementations.

a) Method Overriding

python

class Shape:

    def area(self):

        return 0

 

class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius

 

    def area(self):

        return 3.14 * self.radius * self.radius

 

circle = Circle(5)

print(circle.area())  # Output: 78.5

b) Method Overloading (Using Default Arguments)

Python does not support method overloading directly, but it can be achieved using default parameters.

python

class Math:

    def add(self, a, b, c=0):

        return a + b + c


math_obj = Math()

print(math_obj.add(2, 3))      # Output: 5

print(math_obj.add(2, 3, 4))   # Output: 9


7. Abstraction (Hiding Implementation)

Abstraction hides the implementation details from users using abstract classes.

python

from abc import ABC, abstractmethod

 

class Animal(ABC):

    @abstractmethod

    def make_sound(self):

        pass  # Abstract method

 

class Dog(Animal):

    def make_sound(self):

        return "Woof!"

 

dog = Dog()

print(dog.make_sound())  # Output: Woof!


8. Special Methods (__str__, __repr__, etc.)

Python has special methods (also called dunder methods) that define object behavior.

python

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

 

    def __str__(self):

        return f"Person({self.name}, {self.age})"

 

p = Person("Alice", 30)

print(p)  # Output: Person(Alice, 30)

Other special methods include:

  • __init__() → Constructor
  • __del__() → Destructor
  • __len__() → Defines behavior for len()
  • __getitem__() → Defines behavior for indexing

9. Summary

  • Classes define objects and their behavior.
  • Encapsulation hides data using private/protected members.
  • Inheritance enables reusability by deriving new classes from existing ones.
  • Polymorphism allows different classes to have the same method name.
  • Abstraction hides implementation details using abstract classes.
  • Special methods (__str__, __len__) customize object behavior.

 

Packages in Python

Unit 3 - 3.3  Packages in Python

1. What is a Package in Python?


A package in Python is a collection of related modules stored in a directory. It helps in organizing large codebases by grouping related functionality together.

A package must contain a special file named __init__.py (though optional in Python 3.3+, it's recommended to explicitly include it).

Python packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects. It also allows functionality to be easily shared and distributed across different applications. Packages act like toolboxes, storing and organizing tools (functions and classes) for efficient access and reuse.

2. Structure of a Python Package

A package is simply a directory containing multiple Python modules.

Example Package Structure:

mypackage/

│── __init__.py

│── module1.py

│── module2.py

│── subpackage/

│   ── __init__.py

│   ── module3.py

  • mypackage/ → Main package directory
  • __init__.py → Makes the directory a package
  • module1.py and module2.py → Contain Python functions/classes
  • subpackage/ → A package within a package

3. Creating a Python Package

Step 1: Create a Package Directory

Let's create a package named mypackage.

mkdir mypackage

Step 2: Add an __init__.py File

Create a file inside mypackage/ named __init__.py.

# __init__.py

print("mypackage is imported")

Step 3: Create Some Modules

Create two Python files inside mypackage/:

module1.py

def greet(name):

    return f"Hello, {name}!"

module2.py

def add(a, b):

    return a + b


4. Importing a Package in Python

After creating the package, we can now use it in another Python script.

a) Importing the Whole Package

import mypackage.module1

import mypackage.module2

print(mypackage.module1.greet("Alice"))  # Output: Hello, Alice!

print(mypackage.module2.add(5, 3))  # Output: 8

b) Importing Specific Functions

from mypackage.module1 import greet

from mypackage.module2 import add

print(greet("Bob"))  # Output: Hello, Bob!

print(add(10, 2))  # Output: 12

c) Importing All Modules (Using __init__.py)

Modify __init__.py to automatically import modules:

from .module1 import greet

from .module2 import add

Now, you can directly import the package:

import mypackage

print(mypackage.greet("Charlie"))  # Output: Hello, Charlie!

print(mypackage.add(7, 3))  # Output: 10


5. Subpackages in Python

A subpackage is a package inside another package.

Creating a Subpackage

mypackage/

│── __init__.py

│── module1.py

│── subpackage/

│   ── __init__.py

│   ── module3.py

subpackage/module3.py

def multiply(a, b):

    return a * b

Importing from a Subpackage

from mypackage.subpackage.module3 import multiply

 

print(multiply(4, 5))  # Output: 20


6. Installing and Using External Packages

Python allows installing third-party packages using pip.

Installing a Package

pip install requests

Using an Installed Package

import requests

response = requests.get("https://www.google.com")

print(response.status_code)  # Output: 200


7. Advantages of Using Packages

Modularity – Organizes large codebases.
Reusability – Functions can be reused across multiple projects.
Avoids Name Conflicts – Helps prevent variable/function name clashes.
Scalability – Makes it easy to expand and maintain projects.


8. Summary

  • A package is a directory containing multiple modules and an __init__.py file.
  • Subpackages allow organizing related functionality even further.
  • Importing can be done using import package.module, from package import module, or from package import *.
  • Third-party packages can be installed using pip.

 

Modules in Python

Unit 3 - 3.2 Modules in Python

Modules in Python: A Detailed Overview

In Python, a module is a file containing Python code that defines functions, classes, and variables, making it reusable across different programs. Modules help in organizing code logically and efficiently.


1. Types of Modules in Python

Python modules can be classified into three main types:

  1. Built-in Modules – Pre-installed modules that come with Python (e.g., math, sys, os).
  2. User-defined Modules – Custom modules created by users to organize their code.
  3. Third-party Modules – External modules installed via pip (e.g., numpy, pandas).

2. Creating and Using a Module

A module in Python is simply a .py file containing functions, classes, and variables.

To create a Python module, write the desired code and save that in a file with .py extension. Let’s understand it better with an example:

Creating a Simple Module

Let's create a module named mymodule.py:


# mymodule.py def add(a, b): return a + b def subtract(a, b): return a - b

Importing a Module

To use mymodule.py in another Python script, you can import it using the import statement:


import mymodule result = mymodule.add(5, 3) print(result) # Output: 8

Using from Keyword

You can import specific functions from a module:


from mymodule import add print(add(10, 4)) # Output: 14

Using as Keyword for Aliasing

You can rename a module while importing:


import mymodule as mm print(mm.subtract(10, 5)) # Output: 5

3. Built-in Modules in Python

Python has several built-in modules. Here are a few common ones:

a) math Module – Provides mathematical functions.


import math print(math.sqrt(16)) # Output: 4.0 print(math.factorial(5)) # Output: 120

b) random Module – Used for generating random numbers.


import random print(random.randint(1, 100)) # Output: Random number between 1 and 100

c) datetime Module – Handles date and time.

import datetime current_time = datetime.datetime.now() print(current_time)

d) os Module – Interacts with the operating system.


import os print(os.getcwd()) # Output: Current working directory

4. Installing and Using Third-party Modules

Python allows installation of external modules via pip (Python's package manager).

Installing a Module


pip install numpy

Using the Installed Module


import numpy as np arr = np.array([1, 2, 3]) print(arr) # Output: [1 2 3]

5. Special Module Attributes

Python provides special attributes for modules:


# Inside mymodule.py print(__name__) # Outputs '__main__' if run directly, or 'mymodule' if imported

Checking if a Module is Run Directly


if __name__ == "__main__": print("This script is being run directly")

6. Finding and Listing Module Functions

You can use the dir() function to list all available functions in a module:


import math print(dir(math)) # Lists all functions in math module

7. Python Packages (Modules Inside Folders)

A package is a collection of modules stored in a directory containing an __init__.py file.

Creating a Package


mypackage/ │── __init__.py │── module1.py │── module2.py

Using a Package


from mypackage import module1 module1.some_function()

Conclusion

  • Modules help in reusability and better organization of Python code.
  • Built-in modules provide essential functionalities.
  • User-defined modules can be created for custom functions.
  • Third-party modules can be installed via pip for additional features.
  • Packages organize multiple modules into structured directories.

Sunday, 23 February 2025

String Instructions

What are String Manipulation Instructions in 8086 microprocessors?

String Manipulation Instructions in the 8086 microprocessor architecture are the set of Instructions that are used to manipulate strings in memory. The String manipulation Instructions offer different functionality such as copying, Searching, and Modifying Strings of data. Key String manipulation instruction in 8086 instruction sets includes different instructions such as MOVSB, CMPSB, SCASB, LODSB, STOSB, and other instructions which are going to be discussed further.

Different String Manipulation Instructions

The string is a series of data bytes or words available in memory at consecutive locations. It is either referred as byte string or a word string. Their memory is always allocated in a sequential order. Instructions used to manipulate strings are called string manipulation instructions. Following is the table showing the list of string manipulation instructions:

OPCODE

OPERAND

EXPLANATION

EXAMPLE

REP

instruction

repeat the given instruction till CX != 0

REP MOVSB

REPE

instruction

repeat the given instruction while CX = 0

REPE

REPZ

instruction

repeat the given instruction while ZF = 1

REPZ

REPNE

instruction

repeat the given instruction while CX != 0

REPNE

REPNZ

instruction

repeat the given instruction while ZF = 0

REPNZ

MOVSB

none

moves contents of byte given by DS:SI into ES:DI

MOVSB

MOVSW

none

moves contents of word given by DS:SI into ES:DI

MOVSW

MOVD

none

moves contents of double word given by DS:SI into ES:DI

MOVD

LODSB

none

moves the byte at address DS:SI into AL; SI is incr/decr by 1

LODSB

LODSW

none

moves the word at address DS: SI into AX; SI is incr/decr by 2

LODSW

LODSD

none

moves the double word at address DS:SI into EAX; SI is incr/decr by 4

LODSD

STOSB

none

moves contents of AL to byte address given by ES:DI; DI is incr/dec by 1

STOSB

STOSW

none

moves the contents of AX to the word address given by ES:DI; DI is incr/decr by 2

STOSW

STOSD

none

moves contents of EAX to the DOUBLE WORD address given by ES:DI; DI is incr/decr by 4

STOSD

SCASB

none

compares byte at ES:DI with AL and sets flags according to result

SCASB

SCASW

none

compares word at ES:DI with AX and sets flags

SCASW

SCASD

none

compares double word at ES:DI with EAX and sets flags

SCASD

CMPSB

none

compares byte at ES:DI with byte at DS:SI and sets flags

CMPSB

CMPSW

none

compares word at ES:DI with word at DS:SI and sets flags

CMPSW

CMPSD

none

compares double word at ES:DI with double word at DS:SI and sets flags

CMPSD

Examples of String manipulation instructions in 8086 microprocessor

Given below are some Examples of the String manipulation instructions in 8086 microprocessor

Example of REP with MOVSB Instruction

MOV AX, 7000H    Assign source segment address to AX
MOV DS, AX          Load source segment address into DS
MOV AX, 8000H   Assign destination segment address to AX
MOV CX, 0E0H    Move the length of the string to the counter register CX
MOV SI, 3000H    Assign source index address to SI
MOV DI, 4000H   Assign destination index address to DI
CLD                       Ensure auto-increment mode is set by clearing the direction flag
REP MOVSB         Repeat the move byte from source to destination instruction CX times

Example of REPE With CMPSB Instruction

MOV AX, SEG_STRING1         Move the segment address of STRING1 to AX
MOV DS, AX                             Load it to DS
MOV AX, SEG_STRING2        Move the segment address of STRING2 to AX
MOV ES, AX                              Load it to ES
MOV SI, OFFSET_STRING1   Move the offset of STRING1 to SI
MOV DI, OFFSET_STRING2  Move the offset of STRING2 to DI
MOV CX, 020H                       Move the length of the strings to CX
CLD                                         Clear the direction flag, set auto-increment mode
REPE CMPSB                         Compare the 020H bytes of STRING1 and STRING2,While they are Equal,
                                                 If mismatch is found modify the flags and proceed with further Execution

NOTE: If Both Strings are Equal,CX becomes ZERO,the ZF is set otherwise ZF is reset

Example of REPNE With SCASW Instruction

MOV AX, SEGMENT_STR      Move the segment address of the String to AX
MOV ES, AX                             Load it to ES
MOV DI, OFFSET_STR           Move the offset of String to DI
MOV CX, 020H                        Move the length of the String to CX
MOV AL, WORD_TO_FIND   The word to be scanned for is loaded into AL
CLD                                           Clear the direction flag
REPNE SCASW                        Scan the 020H words of the String until a match to the word is found


Example of LODSB Instruction

MOV CX, 10                      Set CX to the number of bytes to be read
MOV SI, OFFSET_STR    Set SI to point to the start of the string
MOV DI, OFFSET_BUF   Set DI to point to the destination buffer
CLD                                   Clear the direction flag for auto-increment

READ_LOOP:
    LODSB                         Load a byte from the memory location pointed to by SI into AL, and increment SI
    STOSB                         Store the byte in AL at the memory location pointed to by DI, and increment DI
    LOOP READ_LOOP   Decrement CX and loop back if CX is not zero
    HLT                               Halt the processor (assembly language instruction for stopping execution)


Conclusion

In this Article, We have gone through the String manipulation in the 8086 microprocessor which provides efficiently handling operations on strings of data stored in the memory. These instructions enable us to copying, searching and comparing Function in the memory. Also we have gone through the different examples of the Instructions which provides us the clear understanding of the String manipulation instructions set.

 

Desktop Virtualisation

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