在二进制数中查找尾随 0 [英] Finding trailing 0s in a binary number
本文介绍了在二进制数中查找尾随 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何查找二进制数中尾随 0 的数量?基于在二进制数中查找 1 的 K&R bitcount 示例,我对其进行了一些修改以查找尾随 0.
How to find number of trailing 0s in a binary number?Based on K&R bitcount example of finding 1s in a binary number i modified it a bit to find the trailing 0s.
int bitcount(unsigned x)
{
int b;
for(b=0;x!=0;x>>=1)
{
if(x&01)
break;
else
b++;
}
我想回顾一下这个方法.
I would like to review this method.
推荐答案
这是一种并行计算计数以提高效率的方法:
Here's a way to compute the count in parallel for better efficiency:
unsigned int v; // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
这篇关于在二进制数中查找尾随 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文