assemblyx86masmhammingweight

Assembly language program to count number of 1's in binary number


Can someone please help I stuck since few day on this problem. I want to count numbers of 1's in binary value of 2 decimal/hexa. But I am getting incorrect results. Here a code below:

.386  //32-bit processor
.model small, stdcall  
ExitProcess PROTO, deExitCode:DWORD  
.data  
var1 dw 2  
.code  
main PROC  
    LEA ESI,var1  
    MOV EBX, 4 //SIZE OF ARRAY AS 2 binary will be 0010  
    MOV ECX,0  
 L1:CMP EBX,0  
    JE L3  
    MOV EAX,[ESI]  
    CMP EAX,0  
    JE L2  
    INC ECX  
 L2:DEC EBX  
    ADD SI,2  
    JMP L1  
 L3: INVOKE ExitProcess,0  
main ENDP  
END main

Solution

  • If I understand your weird terminology to count numbers of 1's in binary value, you want to count how many bits is set to 1 in a 16bit memory variable var1. A straightforward solution is to load the variable to a register (MOVZX EAX,[var1]) and then 16 times shift the lowest bit to CF (SHR EAX,1) and add the CF to a counter register (ADC ECX,0) each time.

    However, your code seems to count how many of four words in memory has a nonzero value. There are some bugs in it: