Mix (C++ and Assembly) Program to Convert Binary Number into BCD Format

This post explores how to convert a 4-digit binary number (entered as a decimal) into its equivalent Binary Coded Decimal (BCD) form using inline assembly in a C++ program.

#include<iostream.h>
#include<conio.h>

void main()
{
    int a;
    cout << "\n Enter a binary number:";
    cin >> a;
    int t;

    // Converting first digit
    t = a / 1000;
    a = a % 1000;
    asm {
        mov ax, t
        mov bx, 00h
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        add bx, ax
    }

    // Converting second digit
    t = a / 100;
    a = a % 100;
    asm {
        mov ax, t
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        add bx, ax
    }

    // Converting third digit
    t = a / 10;
    a = a % 10;
    asm {
        mov ax, t
        rol ax, 1
        rol ax, 1
        rol ax, 1
        rol ax, 1
        add bx, ax
    }

    // Converting fourth digit
    t = a;
    asm {
        mov ax, t
        add bx, ax
        mov a, bx
    }

    cout << "\n BCD is:" << a;
    getch();
}

Understanding the Code

Variable Declaration
int a; → Stores the binary input from the user.
int t; → Temporarily holds the digit currently being processed.

User Input
The program prompts the user to input a four-digit number representing binary digits (e.g., 0011 = 3).

Inline Assembly Conversion

The number is broken into individual digits:

  1. First Digit
    • Extracted by dividing by 1000.
    • Shifted left (ROL) 12 times (3 times per BCD digit × 4 digits) to adjust its binary weight.
  2. Second Digit
    • Extracted by dividing the remaining number by 100.
    • Shifted 8 times for proper placement in BCD.
  3. Third Digit
    • Extracted by dividing the remaining number by 10.
    • Shifted 4 times.
  4. Fourth Digit
    • No shifting required. Simply added.

Each digit’s binary value is accumulated in register BX, which is finally stored back into a.

Output Display
The final result stored in a (representing the BCD) is printed using cout.


Output

 Enter a binary number:36
 BCD is:54

Output Explanation

If you enter 36 (in binary = 0011 0110), the result is converted to 54 in decimal. This conversion is achieved by shifting and accumulating the binary weights in the correct positions for BCD.

Leave a Reply

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