Wireshark 2.9.0-477-g68ec514b The Wireshark network protocol analyzer

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

bits_ctz.h
1 /*
2 * bitz_ctz.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_CTZ_H__
12 #define __WSUTIL_BITS_CTZ_H__
13
14 #include <glib.h>
15
16 /* ws_ctz == trailing zeros == position of lowest set bit [0..63] */
17 /* ws_ilog2 == position of highest set bit == 63 - leading zeros [0..63] */
18
19 /* The return value of both ws_ctz and ws_ilog2 is undefined for x == 0 */
20
21 #if defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
22
23 static inline int
24 ws_ctz(guint64 x)
25 {
26 return __builtin_ctzll(x);
27 }
28
29 static inline int
30 ws_ilog2(guint64 x)
31 {
32 return 63 - __builtin_clzll(x);
33 }
34
35 #else
36
37 static inline int
38 __ws_ctz32(guint32 x)
39 {
40 /* From http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup */
41 static const guint8 table[32] = {
42 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
43 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
44 };
45
46 return table[((guint32)((x & -(gint32)x) * 0x077CB531U)) >> 27];
47 }
48
49 static inline int
50 ws_ctz(guint64 x)
51 {
52 guint32 hi = x >> 32;
53 guint32 lo = (guint32) x;
54
55 if (lo == 0)
56 return 32 + __ws_ctz32(hi);
57 else
58 return __ws_ctz32(lo);
59 }
60
61 static inline int
62 __ws_ilog2_32(guint32 x)
63 {
64 /* From http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn */
65 static const guint8 table[32] = {
66 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
67 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
68 };
69
70 x |= x >> 1;
71 x |= x >> 2;
72 x |= x >> 4;
73 x |= x >> 8;
74 x |= x >> 16;
75
76 return table[((guint32)(x * 0x07C4ACDDU)) >> 27];
77 }
78
79 static inline int
80 ws_ilog2(guint64 x)
81 {
82 guint32 hi = x >> 32;
83 guint32 lo = (guint32) x;
84
85 if (hi == 0)
86 return __ws_ilog2_32(lo);
87 else
88 return 32 + __ws_ilog2_32(hi);
89 }
90
91 #endif
92
93 #endif /* __WSUTIL_BITS_CTZ_H__ */