Search code examples
clinux-kernelbit-manipulationlinux-device-driverdevice-driver

Kernel macro for counting bits set


Is there a standard Linux Kernel bit operation macro, which returns the number of bits set in an unsigned long ?


Solution

  • You can use:

    hweight_long

    function in include/linux/bitops.h

    Othwerwise Linux kernel uses gcc with GNU extensions and gcc also provides these builtins:

    Built-in Function: int __builtin_popcount (unsigned int x) Returns the number of 1-bits in x.

    Built-in Function: int __builtin_popcountl (unsigned long) Similar to __builtin_popcount, except the argument type is unsigned long.

    http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html