为什么计算位数很有用?

发布于 2024-08-28 16:53:32 字数 557 浏览 5 评论 0原文

我已经看到了许多关于计算插入类型输入中设置位数的问题,但它为什么有用?

对于那些寻找有关位计数算法的人来说,看这里:

  1. 计算无符号长序列中的公共位
  2. 计算无符号整数中的位转换
  3. 如何计算32位整数中设置的位数?

I've seen the numerous questions about counting the number of set bits in an insert type of input, but why is it useful?

For those looking for algorithms about bit counting, look here:

  1. Counting common bits in a sequence of unsigned longs
  2. Fastest way to count number of bit transitions in an unsigned int
  3. How to count the number of set bits in a 32-bit integer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

可爱咩 2024-09-04 16:53:32

您可以将一串位视为一个集合,其中 1 表示相应元素的集合成员资格。因此,位计数可以为您提供该集合的总体计数

实际应用包括压缩、加密和纠错码。请参阅 wikipedia.org/wiki/Hamming_weightwikipedia.org/wiki/Hamming_distance

You can regard a string of bits as a set, with a 1 representing membership of the set for the corresponding element. The bit count therefore gives you the population count of the set.

Practical applications include compression, cryptography and error-correcting codes. See e.g. wikipedia.org/wiki/Hamming_weight and wikipedia.org/wiki/Hamming_distance.

澜川若宁 2024-09-04 16:53:32

如果您正在实施自己的奇偶校验方案,您可能需要计算位数。 (当然,一般来说,我宁愿使用别人的。)如果您正在模拟一台旧计算机并想要跟踪它在原始计算机上运行的速度,有些计算机具有乘法指令,其速度随数字而变化1 位。

我想不出在过去十年左右的时间里我有什么时候想做这件事,所以我怀疑这更多的是一个编程练习而不是实际需要。

If you're rolling your own parity scheme, you might want to count the number of bits. (In general, of course, I'd rather use somebody else's.) If you're emulating an old computer and want to keep track of how fast it would have run on the original, some had multiplication instructions whose speed varied with the number of 1 bits.

I can't think of any time I've wanted to do it over the past ten years or so, so I suspect this is more of a programming exercise than a practical need.

装纯掩盖桑 2024-09-04 16:53:32

以一种讽刺的方式,它对于面试问题很有用,因为它需要一些详细的低级思维,并且似乎没有作为计算机科学课程中的标准算法来教授。

In an ironic sort of fashion, it's useful for an interview question because it requires some detailed low-level thinking and doesn't seem to be taught as a standard algorithm in comp sci courses.

醉生梦死 2024-09-04 16:53:32

有些人喜欢使用位图来指示“东西”的存在/不存在。

有一个简单的技巧可以隔离一个字中最低有效的 1 位,将其转换为它下面的位中的 1 位,然后您可以通过计算 1 位来找到位数。

countbits((x XOR (x-1)))-1;

观察它的工作情况。

Let x =     00101100
Then x-1 =  00101011
x XOR x-1 = 00000111

其中设置了 3 位,因此位 2 是原始字中最低有效的 1 位

Some people like to use bitmaps to indicate presence/absence of "stuff".

There's a simple hack to isolate the least-significant 1 bit in a word, convert it to a field of ones in the bits below it, and then you can find the bit number by counting the 1-bits.

countbits((x XOR (x-1)))-1;

Watch it work.

Let x =     00101100
Then x-1 =  00101011
x XOR x-1 = 00000111

Which has 3 bits set, so bit 2 was the least-significant 1-bit in the original word

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文