Wireshark  4.3.0
The Wireshark network protocol analyzer
bits_count_ones.h
Go to the documentation of this file.
1 
10 #ifndef __WSUTIL_BITS_COUNT_ONES_H__
11 #define __WSUTIL_BITS_COUNT_ONES_H__
12 
13 #include <inttypes.h>
14 
15 /*
16  * The variable-precision SWAR algorithm is an interesting way to count
17  * the number of bits set in an integer:
18  *
19  * https://www.playingwithpointers.com/blog/swar.html
20  *
21  * See
22  *
23  * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36041
24  * https://danluu.com/assembly-intrinsics/
25  *
26  * for discussions of various forms of population-counting code on x86.
27  *
28  * See
29  *
30  * https://docs.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64
31  *
32  * for MSVC's population count intrinsics.
33  *
34  * Note that not all x86 processors support the POPCOUNT instruction.
35  *
36  * Other CPUs may have population count instructions as well.
37  */
38 
39 static inline int
40 ws_count_ones(const uint64_t x)
41 {
42  uint64_t bits = x;
43 
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);
47 
48  return (int)((bits * UINT64_C(0x0101010101010101)) >> 56);
49 }
50 
51 #endif /* __WSUTIL_BITS_COUNT_ONES_H__ */