Mix (C++ and Assembly) Program to Add Two 8 bit Numbers

This blog post will guide you through a C++ program that performs the addition of two numbers using inline assembly. While modern compilers provide high-level arithmetic operations, understanding inline assembly can help in optimizing performance and understanding low-level interactions with the CPU. Let’s explore this step-by-step!

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main()
{
    clrscr();
    short int a, b, c;
    
    cout << "Enter First Number: ";
    cin >> a;
    cout << "Enter Second Number: ";
    cin >> b;
    
    asm mov ax, a
    asm mov ah, 00h
    asm mov bx, b
    asm mov bh, 00h
    asm add al, bl
    asm mov c, ax
    
    cout << "Result: ";
    cout << c;
    
    getch();
}

Understanding the Code

Variable Declarations

  • short int a, b, c; → Declares three short integers to store input values and the result.

User Input

  • The program takes two user inputs and stores them in a and b.

Inline Assembly Operations

  • asm mov ax, a → Moves the first number into register AX.
  • asm mov ah, 00h → Clears the upper byte of AX to ensure correct 16-bit arithmetic.
  • asm mov bx, b → Moves the second number into register BX.
  • asm mov bh, 00h → Clears the upper byte of BX.
  • asm add al, bl → Adds the lower bytes (8-bit addition) and stores the result in AL.
  • asm mov c, ax → Stores the final result back into the variable c.

Output Display

  • The computed sum is displayed using cout.

Output

When the program runs, it follows these steps:

  1. User Input Stage
    • The program prompts the user to enter two numbers.
    • For example, the user inputs 12 and 51.
  2. Processing with Inline Assembly
    • The values 12 and 51 are stored in CPU registers.
    • The assembly instructions perform an addition operation.
    • The sum of 12 and 51 is computed as 63.
    • The result is then stored in a variable.
  3. Displaying the Output
    • The computed sum is displayed to the user.
    • The final output appears as:
Enter First Number: 12
Enter Second Number: 51
Result: 63

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.