Wireshark  2.9.0-477-g68ec514b
The Wireshark network protocol analyzer
bits_count_ones.h
1 /*
2  * bits_count_ones.h
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * SPDX-License-Identifier: GPL-2.0-or-later
9  */
10 
11 #ifndef __WSUTIL_BITS_COUNT_ONES_H__
12 #define __WSUTIL_BITS_COUNT_ONES_H__
13 
14 #include <glib.h>
15 
16 /*
17  * The variable-precision SWAR algorithm is an interesting way to count
18  * the number of bits set in an integer:
19  *
20  * http://playingwithpointers.com/swar.html
21  *
22  * See
23  *
24  * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36041
25  * https://danluu.com/assembly-intrinsics/
26  *
27  * for discussions of various forms of population-counting code on x86.
28  *
29  * See
30  *
31  * https://msdn.microsoft.com/en-us/library/bb385231.aspx
32  *
33  * for MSVC's population count intrinsics.
34  *
35  * Note that not all x86 processors support the POPCOUNT instruction.
36  *
37  * Other CPUs may have population count instructions as well.
38  */
39 
40 static inline int
41 ws_count_ones(const guint64 x)
42 {
43  guint64 bits = x;
44 
45  bits = bits - ((bits >> 1) & G_GUINT64_CONSTANT(0x5555555555555555));
46  bits = (bits & G_GUINT64_CONSTANT(0x3333333333333333)) + ((bits >> 2) & G_GUINT64_CONSTANT(0x3333333333333333));
47  bits = (bits + (bits >> 4)) & G_GUINT64_CONSTANT(0x0F0F0F0F0F0F0F0F);
48 
49  return (int)((bits * G_GUINT64_CONSTANT(0x0101010101010101)) >> 56);
50 }
51 
52 #endif /* __WSUTIL_BITS_COUNT_ONES_H__ */