计算一个字节中的零和一的数目 [英] counting number of zeros and ones in a byte
本文介绍了计算一个字节中的零和一的数目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以前发布过一个程序来查找一个字节中的总1s.现在,我尝试查找一个字节中的0.以下是我的代码:
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,08H
MOV BX,0000H
MOV DX,0000H
Zero:
SHR AL,01H
JZ ero
JNZ ZrO
ero: INC BX
ZrO: INC DX
LOOP Zero
hlt
程序没有给出正确的答案.你猜我在哪里错了吗?
The program isn't giving the right answer. Any guesses where am I wrong?
推荐答案
从AL移出的位进入进位标志,而不是零标志.更改您的条件跳转:
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
顺便说一句,在新的英特尔处理器(NEHALEM)上有专门针对此任务的说明: https://www.felixcloutier.com/x86/popcnt
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.
这篇关于计算一个字节中的零和一的数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文