Mix (C++ and Assembly) Program to Add Two 16 bit Numbers

While high-level languages like C++ are well known for abstracting away low-level operations, sometimes it’s beneficial to peek under the hood to see how things really work at the machine level. In this post, we’ll explore a simple C++ program that incorporates inline assembly to add two 16-bit numbers.

#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 (binary 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 and b.

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 mov c, ax → Moves the result from AX into variable c.

Output Display

  • The final sum stored in c is displayed to the user using cout.

Output

Enter First Number:500
Enter Second Number:617
Result:1117

As shown above, the addition of 500 and 617 gives a result of 1117 — a straightforward binary sum. That’s all!

Leave a Reply

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