Bit count
The program counts the number of bits set to 1 in the binary representation of a given number.
Program source code
title .model small .stack 100h data segment public fmtout db "Decimal number %d in binary %b has %d bits set to 1.\n\0" number dw 17763 data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure mov ax, number ; Copy the value of the number variable into the ax register call BitCount ; Call the BitCount procedure push ax ; 4th: Save the value returned by the BitCount function on the stack push number ; 3rd: Save the value of the number variable on the stack push number ; 2nd: Save the value of the number variable on the stack lea ax, ds:[fmtout] ; 1st: load the address of the fmtout format string into ax call PrintFormatString ; Call the PrintFormatString procedure add sp, 6 ; Align the stack xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure BitCount proc ; Start of the BitCount procedure push cx ; Save the cx register value on the stack push dx ; Save the dx register value on the stack mov cx, 16 ; Set the counter to 16 (bit count) mov dx, ax ; Copy the ax register value into the dx register xor ax, ax ; Clear the ax register BitCountLoop: shr dx, 1 ; Shift the value in the dx register one bit to the right jnc Skip ; If CF=0, then jump to the Skip label inc ax ; Increment the ax register value (number of bits set) Skip: loop BitCountLoop ; Loop while the cx register is not equal to 0 pop dx ; Pop the value from the stack into the dx register pop cx ; Pop the value from the stack into the cx register ret ; Return from the procedure BitCount endp ; End of the BitCount procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
Decimal number 17763 in binary 0100 0101 0110 0011 has 7 bits set to 1.
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".