What is the algorithm to count the number of 1 bits in a 64-bit integer?

69 Views Asked by At

For example:

./bit_count 0x123456789abcdef0 bit_count(0x123456789abcdef0) returned 32

What would be an algorithm to count the number of 1-bits in the 64-bit integer value that was passed in to the given function above.

Any help would be much appreciated?

1

There are 1 best solutions below

1
Vlad from Moscow On

One of approaches is the following

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

The program output is

32