update epan/dissectors/pidl/drsuapi/drsuapi.idl from samba
[wireshark-sm.git] / wsutil / bits_count_ones.h
bloba77025d7f8b8c72e9af60f1d57d089d53d8e422a
1 /** @file
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
8 */
10 #ifndef __WSUTIL_BITS_COUNT_ONES_H__
11 #define __WSUTIL_BITS_COUNT_ONES_H__
13 #include <inttypes.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
21 * See
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.
28 * See
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.
39 static inline int
40 ws_count_ones(const uint64_t x)
42 uint64_t bits = 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__ */