c语言32位整形怎么设置,如何计算32位整数中的设置位数?

在我看来,“最佳”解决方案是另一个程序员(或两年后的原始程序员)可以阅读而没有大量评论的解决方案。你可能想要一些已经提供的最快或最聪明的解决方案,但我更喜欢可读性而不是聪明。

unsigned int bitCount (unsigned int value) {

unsigned int count = 0;

while (value > 0) {           // until all bits are zero

if ((value & 1) == 1)     // check lower bit

count++;

value >>= 1;              // shift bits, removing lower bit

}

return count;

}

如果你想要更快的速度(假设你记录好以帮助你的继任者),你可以使用表查找:

// Lookup table for fast calculation of bits set in 8-bit unsigned char.

static unsigned char oneBitsInUChar[] = {

//  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F (

//  =====================================================

0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 0n

1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1n

: : :

4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, // Fn

};

// Function for fast calculation of bits set in 16-bit unsigned short.

unsigned char oneBitsInUShort (unsigned short x) {

return oneBitsInUChar [x >>    8]

+ oneBitsInUChar [x &  0xff];

}

// Function for fast calculation of bits set in 32-bit unsigned int.

unsigned char oneBitsInUInt (unsigned int x) {

return oneBitsInUShort (x >>     16)

+ oneBitsInUShort (x &  0xffff);

}

虽然这些依赖于特定的数据类型大小,因此它们不具备可移植性。但是,由于许多性能优化无论如何都不可移植,这可能不是问题。如果你想要便携性,我会坚持使用可读的解决方案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值