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

While modern high-level languages like C++ abstract away many low-level operations, sometimes it’s useful to get closer to the hardware to understand how things work under the hood. This example demonstrates how to subtract two 8-bit numbers using inline assembly in a simple C++ program.

#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      // Move 'a' into AX
    asm mov ah, 00h    // Ensure AH is cleared
    asm mov bx, b      // Move 'b' into BX
    asm mov bh, 00h    // Ensure BH is cleared
    asm sub al, bl     // Subtract BL from AL
    asm mov c, ax      // Store result in 'c'

    cout << "Result:";
    cout << c;

    getch();
}

Understanding the Code

Variable Declarations

short int a, b, c; → Declares three integer variables to store the two input values and the result.

User Input

  • The program prompts the user to enter two integer values, which are then stored in variables a and b.

Inline Assembly Operations

  • asm mov ax, a → Moves the value of a into register AX.
  • asm mov ah, 00h → Clears the higher byte (AH) to ensure no garbage data affects the result.
  • asm mov bx, b → Moves the value of b into register BX.
  • asm mov bh, 00h → Clears the higher byte (BH) for the same reason.
  • asm sub al, bl → Subtracts the lower byte of b (BL) from the lower byte of a (AL); result is in AL.
  • asm mov c, ax → Moves the result from AX into the variable c.

Output Display

  • The final result stored in c is displayed to the user using cout.

Output

Enter First Number:51
Enter Second Number:12                                                          
Result:39  

The program subtracts the second number from the first and displays the result.

One thought on “Mix (C++ and Assembly) Program to Subtract Two 8 bit Numbers”

Leave a Reply

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