This post demonstrates how to count the number of 0s and 1s in the binary representation of an integer using inline assembly in a C++ program. This is an excellent example of bit-level operations using low-level assembly instructions.
#include<iostream.h>
#include<conio.h>
void main()
{
int ip, n0, n1;
cout << "\n Enter Input:";
cin >> ip;
asm {
mov ax, ip // Move input number into AX register
mov bx, 00h // Initialize BX (zero counter) to 0
mov cx, 10h // Set CX as loop counter (16 iterations for 16 bits)
mov dx, 00h // Initialize DX (one counter) to 0
}
up:
asm {
rol ax, 1 // Rotate AX left by 1 bit (MSB to LSB)
jc one // If carry flag is set, it's a 1 (go to one)
inc bx // Otherwise, increment zero counter
jmp nxt // Jump to nxt
}
one:
asm {
inc dx // Increment one counter
}
nxt:
asm {
dec cx // Decrement loop counter
jnz up // If CX not zero, repeat loop
mov n0, bx // Move final zero count to n0
mov n1, dx // Move final one count to n1
}
cout << "\n No of zeros:" << n0;
cout << "\n No of ones:" << n1;
getch();
}
Understanding the Code
Variable Declarations
int ipโ Stores the user input.int n0, n1โ Used to store the number of0s and1s, respectively.
User Input
- Prompts the user to enter a number, which is stored in
ip.
Inline Assembly Instructions Explanation (8086)
mov ax, ipโ Moves the value ofipinto register AX.mov bx, 00hโ Initializes BX register (used to count zeros) to 0.mov cx, 10hโ Initializes CX with0x10(16 decimal), the number of bits to check.mov dx, 00hโ Initializes DX register (used to count ones) to 0.
Loop Logic
rol ax, 1โ Rotates AX register left by 1 bit. The MSB becomes the LSB, and the previous MSB is stored in the carry flag (CF).jc oneโ Jumps to labeloneif the carry flag is set, indicating a 1.inc bxโ Increments BX register if the current bit is 0.jmp nxtโ Jumps to labelnxtto continue looping.inc dxโ Increments DX register if the current bit is 1.dec cxโ Decrements the loop counter.jnz upโ Jumps back to the labelupif CX is not zero.mov n0, bxโ Moves the zero count from BX to variablen0.mov n1, dxโ Moves the one count from DX to variablen1.
Output Display
Outputs the number of zeros and ones in the binary representation of the input number..
Output
Enter Input:12
No of zeros:14
No of ones:2
Output Explanation
If you enter 12, its binary representation is 0000 0000 0000 1100. Out of the 16 bits, 14 are 0s and 2 are 1s. The program successfully counts each using inline assembly and displays the result.