计算 64 位(长、大)整数中的位数? [英] Count number of bits in a 64-bit (long, big) integer?

查看:27
本文介绍了计算 64 位(长、大)整数中的位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于 32 位的this SO question,但是关于 64 位的数字呢?我是否应该只屏蔽上下 4 个字节,对 32 位进行计数,然后将它们加在一起?

I have read through this SO question about 32-bits, but what about 64-bit numbers? Should I just mask the upper and lower 4 bytes, perform the count on the 32-bits and then add them together?

推荐答案

您可以在这里找到 64 位版本 http://en.wikipedia.org/wiki/Hamming_weight

You can find 64 bit version here http://en.wikipedia.org/wiki/Hamming_weight

是这样的

static long NumberOfSetBits(long i)
{
    i = i - ((i >> 1) & 0x5555555555555555);
    i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333);
    return (((i + (i >> 4)) & 0xF0F0F0F0F0F0F0F) * 0x101010101010101) >> 56;
}

这是此处代码形式的 64 位版本如何计算 32 位整数中设置的位数?

This is a 64 bit version of the code form here How to count the number of set bits in a 32-bit integer?

使用 Joshua 的建议,我会将其转换为:

Using Joshua's suggestion I would transform it into this:

static int NumberOfSetBits(ulong i)
{
    i = i - ((i >> 1) & 0x5555555555555555UL);
    i = (i & 0x3333333333333333UL) + ((i >> 2) & 0x3333333333333333UL);
    return (int)(unchecked(((i + (i >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56);
}

编辑:我在测试 32 位版本时发现了一个错误.我添加了缺少的括号.求和应该在按位 & 之前完成,在最后一行

EDIT: I found a bug while testing 32 bit version. I added missing parentheses. The sum should be done before bitwise &, in the last line

EDIT2 为 ulong 添加了更安全的版本

EDIT2 Added safer version for ulong

这篇关于计算 64 位(长、大)整数中的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆