12 #ifndef BITMATH_FUNC_HPP
13 #define BITMATH_FUNC_HPP
34 static inline uint
GB(
const T x,
const uint8 s,
const uint8 n)
36 return (x >> s) & (((T)1U << n) - 1);
59 template <
typename T,
typename U>
60 static inline T
SB(T &x,
const uint8 s,
const uint8 n,
const U d)
62 x &= (T)(~((((T)1U << n) - 1) << s));
84 template <
typename T,
typename U>
85 static inline T
AB(T &x,
const uint8 s,
const uint8 n,
const U i)
87 const T mask = ((((T)1U << n) - 1) << s);
88 x = (T)((x & ~mask) | ((x + (i << s)) & mask));
104 template <
typename T>
105 static inline bool HasBit(
const T x,
const uint8 y)
107 return (x & ((T)1U << y)) != 0;
122 template <
typename T>
123 static inline T
SetBit(T &x,
const uint8 y)
125 return x = (T)(x | ((T)1U << y));
138 #define SETBITS(x, y) ((x) |= (y))
152 template <
typename T>
153 static inline T
ClrBit(T &x,
const uint8 y)
155 return x = (T)(x & ~((T)1U << y));
168 #define CLRBITS(x, y) ((x) &= ~(y))
182 template <
typename T>
185 return x = (T)(x ^ ((T)1U << y));
190 extern const uint8
_ffb_64[64];
202 #define FIND_FIRST_BIT(x) _ffb_64[(x)]
220 if ((value & 0xFF) == 0) {
240 template <
typename T>
243 return value &= (T)(value - 1);
252 template <
typename T>
262 for (num = 0; value != 0; num++) {
263 value &= (T)(value - 1);
275 template <
typename T>
278 return value != 0 && (value & (value - 1)) == 0;
287 template <
typename T>
290 return (value & (value - 1)) == 0;
302 template <
typename T>
303 static inline T
ROL(
const T x,
const uint8 n)
305 return (T)(x << n | x >> (
sizeof(x) * 8 - n));
317 template <
typename T>
318 static inline T
ROR(
const T x,
const uint8 n)
320 return (T)(x >> n | x << (
sizeof(x) * 8 - n));
340 #define FOR_EACH_SET_BIT_EX(Tbitpos_type, bitpos_var, Tbitset_type, bitset_value) \
342 Tbitset_type ___FESBE_bits = (bitpos_var = (Tbitpos_type)0, bitset_value); \
343 ___FESBE_bits != (Tbitset_type)0; \
344 ___FESBE_bits = (Tbitset_type)(___FESBE_bits >> 1), bitpos_var++ \
346 if ((___FESBE_bits & 1) != 0)
361 #define FOR_EACH_SET_BIT(bitpos_var, bitset_value) FOR_EACH_SET_BIT_EX(uint, bitpos_var, uint, bitset_value)
363 #if defined(__APPLE__)
368 #define BSWAP32(x) ((uint32)CFSwapInt32(x))
369 #define BSWAP16(x) ((uint16)CFSwapInt16(x))
370 #elif defined(_MSC_VER)
372 #define BSWAP32(x) (_byteswap_ulong(x))
373 #define BSWAP16(x) (_byteswap_ushort(x))
382 #if !defined(__ICC) && defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ >= 3))
384 return (uint32)__builtin_bswap32((int32)x);
386 return ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00) | ((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000);
397 return (x >> 8) | (x << 8);