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
andb
.
Inline Assembly Operations
asm mov ax, a
→ Moves the value ofa
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 ofb
into register BX.asm mov bh, 00h
→ Clears the higher byte (BH) for the same reason.asm sub al, bl
→ Subtracts the lower byte ofb
(BL) from the lower byte ofa
(AL); result is in AL.asm mov c, ax
→ Moves the result from AX into the variablec
.
Output Display
- The final result stored in
c
is displayed to the user usingcout
.
Output
Enter First Number:51
Enter Second Number:12
Result:39
The program subtracts the second number from the first and displays the result.
I’m looking for a part can u help me