3 * Copyright (C) 2009 Daniel Borkmann <borkmann@gnumaniacs.org>
4 * Copyright (C) 2009 Thomas Reinhardt <treinhar@imn.htwk-leipzig.de>
5 * Copyright (C) 2009 Rico Tilgner <rtilgner@imn.htwk-leipzig.de>
8 * Faculty of Computer Science, Mathematics and Natural Sciences,
9 * Leipzig University of Applied Sciences (HTWK Leipzig)
13 * Some stuff is from the Hacker's Delight book, some from
14 * http://graphics.stanford.edu/~seander/bithacks.html, some
15 * from Quake 3 Arena and some from ourselfes.
23 /* Inverse square root for floats */
24 static inline float finvsqrt(float x
)
31 bf
= 0x5F3759DF - (bf
>> 1);
33 x
= x
* (1.5f
- x_half
* x
* x
);
38 /* Branch-free absolute function for floats */
39 static inline float fabs2(float x
)
50 /* Branch-free compare function for two integers */
51 static inline int cmp(int x
, int y
)
53 return (x
> y
) - (x
< y
);
56 /* Check if two integers have opposite signs */
57 static inline int opp_sign(int x
, int y
)
62 /* Returns sign of interger */
63 static inline int sign(int x
)
65 return (+1 | (x
>> (sizeof(int) * 8 - 1)));
68 /* Return absolute value of integer */
69 static inline unsigned int iabs(int x
)
71 int const mask
= x
>> sizeof(int) * 8 - 1;
72 return (x
+ mask
) ^ mask
;
75 /* Return minimum of x,y */
76 static inline int min(int x
, int y
)
78 return y
^ ((x
^ y
) & -(x
< y
));
81 /* Return maximum of x,y */
82 static inline int max(int x
, int y
)
84 return x
^ ((x
^ y
) & -(x
< y
));
87 /* Determine if x is power of 2 */
88 static inline int ispow2(unsigned int x
)
90 return x
&& !(x
& (x
- 1));
93 /* if (cond) reg |= mask; else reg &= ~mask; */
94 static inline unsigned int cond_set_bit(bool cond
, unsigned int mask
,
97 (*reg
) ^= (-cond
^ (*reg
)) & mask
;
100 /* if (cond) reg |= mask; else reg &= ~mask; */
101 static inline unsigned int cond_set_bit2(int cond
, unsigned int mask
,
104 (*reg
) ^= (-(!!(cond
)) ^ (*reg
)) & mask
;
107 /* Negate is negate is true */
108 static inline int cond_negate(bool negate
, int x
)
110 return (x
^ -negate
) + negate
;
113 /* Count Bits in x */
114 static inline unsigned int count_bits_set(unsigned int x
)
118 for (c
= 0; v
; c
++) {
125 /* Square root calculus for integers */
126 static inline int sqrt(unsigned x
)
147 /* Cube root calculus for integers */
148 static inline int cbrt(unsigned int x
)
158 b
= (3 * y
* (y
+ 1) + 1) << s
;
170 /* Exponentiation function for integers */
171 static inline int exp(int x
, unsigned n
)
188 #endif /* BITHACKS_H */