计算64位整数中1的个数的算法是什么? [重复]

问题描述 投票:0回答:1
例如:

./bit_count 0x123456789abcdef0 bit_count(0x123456789abcdef0) 返回 32

计算传递给上面给定函数的 64 位整数值中 1 位的数量的算法是什么。

如有任何帮助,将不胜感激?

c binary hex bitwise-operators bit-shift
1个回答
0
投票
其中一种方法如下

#include <stdint.h> #include <stdio.h> size_t bit_count( uint64_t n ) { size_t count = 0; for (; n != 0; n &= n - 1) { ++count; } return count; } int main( void ) { printf( "%zu\n", bit_count( 0x123456789abcdef0 ) ); }
    
© www.soinside.com 2019 - 2024. All rights reserved.