This post demonstrates how to convert a Binary Coded Decimal (BCD) number into its binary equivalent using inline assembly within a C++ program. The conversion is done by isolating and processing each BCD digit and calculating its decimal equivalent.
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
cout << "\n Enter a BCD number:";
cin >> a;
int t;
int r = 0;
int i;
asm {
mov ax, a
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
and ax, 000fh
mov i, ax
}
r = r * 10 + i;
asm {
mov ax, a
ror ax, 1
ror ax, 1
ror ax, 1
ror ax, 1
and ax, 000fh
mov i, ax
}
r = r * 10 + i;
asm {
mov ax, a
and ax, 000fh
mov i, ax
}
r = r * 10 + i;
cout << "\n Binary Equivalent:" << r;
getch();
}
Understanding the Code
Variable Declarations
int a;
→ Holds the input BCD number.int t;
→ Temporary variable used in calculations.int r = 0;
→ Stores the final binary result.int i;
→ Used to hold individual digits extracted using assembly.
User Input
The user is prompted to enter a BCD number, which is stored in variable a
.
Inline Assembly Breakdown
The input is treated as a 3-digit BCD value. Each digit is extracted and added to r
with its proper positional value:
- First Digit (Hundreds place):
- The number is rotated 8 bits to the right to bring the most significant BCD digit to the lower nibble.
- It is masked with
000fh
to isolate the digit. - The result is multiplied by 100 (indirectly, via
r = r * 10 + i
across three steps).
- Second Digit (Tens place):
- The number is rotated 4 bits to the right.
- Again, the digit is isolated with
and ax, 000fh
. - The digit is added to the result as the tens place.
- Third Digit (Units place):
- The lower nibble is directly extracted.
- Added as the unit digit to the result.
Output Display
The final decimal equivalent of the BCD is printed using cout
.
Output
Enter a BCD number:54
Binary Equivalent:36
Output Explanation
If you enter 54
(as BCD), it is internally interpreted as 0101 0100
. This represents the decimal number 54. The assembly code processes each BCD digit and converts it into its correct decimal (binary) equivalent. The result 36
is shown as the actual decimal value encoded by the BCD input.