3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
10 #ifndef __WSUTIL_BITS_COUNT_ONES_H__
11 #define __WSUTIL_BITS_COUNT_ONES_H__
16 * The variable-precision SWAR algorithm is an interesting way to count
17 * the number of bits set in an integer:
19 * https://www.playingwithpointers.com/blog/swar.html
23 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36041
24 * https://danluu.com/assembly-intrinsics/
26 * for discussions of various forms of population-counting code on x86.
30 * https://docs.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64
32 * for MSVC's population count intrinsics.
34 * Note that not all x86 processors support the POPCOUNT instruction.
36 * Other CPUs may have population count instructions as well.
40 ws_count_ones(const uint64_t x
)
44 bits
= bits
- ((bits
>> 1) & UINT64_C(0x5555555555555555));
45 bits
= (bits
& UINT64_C(0x3333333333333333)) + ((bits
>> 2) & UINT64_C(0x3333333333333333));
46 bits
= (bits
+ (bits
>> 4)) & UINT64_C(0x0F0F0F0F0F0F0F0F);
48 return (int)((bits
* UINT64_C(0x0101010101010101)) >> 56);
51 #endif /* __WSUTIL_BITS_COUNT_ONES_H__ */