NASM:计数如何在一32位号码许多位被设置为1 [英] NASM: Count how many bits in a 32 Bit number are set to 1
问题描述
我有一个32位的数字,想知道计数位多少1。
I have a 32 Bit number and want to count know how many bits are 1.
我想这个伪code的:
I'm thinking of this pseudocode:
mov eax, [number]
while(eax != 0)
{
div eax, 2
if(edx == 1)
{
ecx++;
}
shr eax, 1
}
有没有更有效的方法?
Is there a more efficient way?
我使用NASM在x86处理器。
I'm using NASM on a x86 processor.
(我只是用汇编开始的,所以请不要告诉我用从图书馆的extern code,因为我甚至不知道如何将它们;))
(I'm just beginning with assembler, so please do not tell me to use code from extern libraries, because I do not even know how to include them ;) )
(我刚刚发现的http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer其中还包含我的解决办法。还有其他发布的解决方案,但不幸的是我似乎无法弄清楚,我将如何把它们写在汇编语言)
(I just found http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer which also contains my solution. There are other solutions posted, but unfortunatly I can't seem to figure out, how I would write them in assembler)
推荐答案
最有效的方法(在执行时间,无论如何)是有一个查找表。显然,你不会有一个四十亿项表,但你可以下破32位到8位的块,只需要256项表,或进一步分解成4位块,只需要16个条目。祝你好运!
The most efficient way (in terms of execution time, anyway) is to have a lookup table. Obviously you're not going to have a 4-billion entry table, but you could break the 32 bits down into 8-bit chunks and only need a 256-entry table, or further down into 4-bit chunks and only need 16 entries. Good luck!
这篇关于NASM:计数如何在一32位号码许多位被设置为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!