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

Time:10-03

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

CodePudding user response:

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:

  • SIZE OF ARRAY which you have statically defined as var1 is not 4. It would have to be defined as var1 DW 2,3,4,5 ; Array of four words.

  • MOV EAX,[ESI] correctly loads AX from var1 but it also loads whatever garbage follows var1 to upper 16 bits of EAX.

  • ADD SI,2 should be ADD ESI,2.

  • Related