While modern high-level languages like C++ abstract away many low-level operations, sometimes it’s useful to dive into assembly-level instructions for greater control and understanding. This example demonstrates subtraction using inline assembly in C++, with the addition of the DAS
instruction to adjust the result for Binary Coded Decimal (BCD) operations.
#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 'a' into AX
asm mov bx, b // Move 'b' into BX
asm sub ax, bx // Subtract BX from AX
asm das // Adjust AX for BCD subtraction
asm mov c, ax // Store result in '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 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 bx, b
→ Moves the value ofb
into register BX.asm sub ax, bx
→ Subtracts the contents of BX from AX.asm das
→ Adjusts the result in AX for Binary Coded Decimal (BCD) representation.asm mov c, ax
→ Moves the result from AX into variablec
.
Output Display
- The final result stored in
c
is displayed to the user usingcout
.
What is DAS (Decimal Adjust after Subtraction)?
The DAS instruction stands for Decimal Adjust after Subtraction. It’s an x86 assembly instruction used specifically for operations involving Binary-Coded Decimal (BCD) values — where each nibble (4 bits) represents a decimal digit ranging from 0 to 9.
DAS is used after subtracting two BCD numbers to adjust the binary result into a valid BCD format.
For example, let’s say:
- You subtract 5 (0101 in BCD) from 9 (1001 in BCD).
- The raw binary result is 4 (0100 in binary), which is already valid in BCD — so DAS won’t make changes in this case.
However, in more complex cases like:
- Subtracting 8 (1000 in BCD) from 3 (0011 in BCD) would result in a borrow and an incorrect BCD digit.
- DAS corrects the result by adjusting the AL register and setting flags accordingly so the final value remains a valid BCD.
In essence, DAS ensures that the result of a BCD subtraction is a valid BCD number, similar to how DAA works for addition.
Sample Output 1
Enter First Number: 999
Enter Second Number: 351
Result: 642
The DAS instruction adjusts the binary result to a valid BCD representation.
Sample Output 2
Enter First Number: 856
Enter Second Number: 237
Result: 619
BCD adjustment ensures proper formatting of the subtraction result.
Sample Output 3
Enter First Number: 500
Enter Second Number: 250
Result: 250
Standard subtraction with BCD-corrected output.