While high-level programming languages like C++ make arithmetic operations incredibly simple, delving into inline assembly offers valuable insights into how the CPU processes instructions under the hood. Hence in this post, we’ll walk through a simple program that uses both C++ and inline assembly to add two integer values. Additionally, we will carry out decimal adjust after addition.
Code
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int a,b,c;
cout<<"Enter First Number:";
cin>>a;
cout<<"Enter Second Number:";
cin>>b;
asm mov ax, a // Move first number into AX
asm mov bx, b // Move second number into BX
asm add ax, bx // Add BX to AX
asm daa // Decimal Adjust AL after Addition
asm mov c, ax // Move result into variable 'c'
cout<<"Result:";
cout<<c;
getch();
}
Understanding the Code
Variable Declarations
int a, b, c;
→ Declares three integer variables to store the two input values and their sum.
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 first number into register AX.asm mov bx, b
→ Moves the second number into register BX.asm add ax, bx
→ Adds the contents of BX to AX; the result is stored in AX.asm daa
→ Decimal Adjust AL after Addition (used for BCD arithmetic).asm mov c, ax
→ Moves the result from AX into variablec
.
Output Display
- The final sum stored in
c
is displayed to the user usingcout
.
What is DAA (Decimal Adjust after Addition)?
The DAA
instruction stands for Decimal Adjust after Addition. It’s an x86 assembly instruction that’s specifically designed to work with Binary-Coded Decimal (BCD) values — a format where each nibble (4 bits) represents a single decimal digit (0–9).
DAA
is used after adding two BCD numbers to correct the result so it forms a valid BCD number.
For example, let’s say:
- You add
9
(1001 in BCD) and5
(0101 in BCD). - The raw binary result is
14
(1110 in binary), but that’s not a valid BCD digit. DAA
corrects it to0001 0100
, which is 1 and 4 — representing decimal 14 in BCD.
Output
Enter First Number: 500
Enter Second Number: 617
Result: 1123
As shown, the inline assembly successfully computes the sum of the two integers and stores the result.