C语言 计算64位整数中1位的算法是什么?[副本]

5sxhfpxr  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(153)

此问题已在此处有答案

Program to count the number of bits set in c(8个回答)
上个月关门了。
举例来说:
./bit_count 0x 123456789 abcdef 0 bit_count(0x 123456789 abcdef 0)返回32
什么是一个算法来计算传入上述给定函数的64位整数值中的1位数。
任何帮助将不胜感激?

6mw9ycah

6mw9ycah1#

方法之一如下

#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 ) );
}

程序输出为

32

相关问题