counting number of zeros and ones in a byte

后端 未结 2 873
死守一世寂寞
死守一世寂寞 2021-01-28 03:41

I previously posted a program to find the total number of 1s in a byte. Now I am trying to find the number of 0s in a byte. Following is my code:

MOV AL,1
MOV CX         


        
2条回答
  •  隐瞒了意图╮
    2021-01-28 03:55

    The bit which is shifted-out from AL goes to the carry-flag, not to the zero-flag. Change your conditional jumps:

        MOV AL,1     ; An investigated byte.    
        MOV CX,08H   ; Number of bits in the byte. 
        MOV BX,0000H ; Result: number of 1s.
        MOV DX,0000H ; Result: number of 0s.
    Zero:SHR AL,01H  ; Shift the byte, least significant bit to CF.
        JNC ZrO
    ero:INC BX      ; Count 1s. 
        JMP Skip
    ZrO:INC DX      ; Count 0s.
    Skip:LOOP Zero   ; Repeat CX times.
        hlt
    

    BTW there is a specialized instruction for this task on new Intel processors (NEHALEM): https://www.felixcloutier.com/x86/popcnt

        MOV AL,1     ; An investigated byte.  
        XOR AH,AH    
        POPCNT BX,AX ; Count the number of 1s in AX and put result to BX.
        MOV DX,8
        SUB DX,BX    ; The number of 0s in AL is 8-BX.
    

提交回复
热议问题