next_power_of_two bit hack function

This commit is contained in:
Imbus 2025-09-08 05:02:38 +02:00
parent 45ad16efb0
commit f01b71f4a6

View file

@ -4,6 +4,7 @@
/* /*
* Give hints to the compiler for branch prediction optimization. * Give hints to the compiler for branch prediction optimization.
*/ */
#include <stdint.h>
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 2)) #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 2))
#define likely(c) (__builtin_expect(!!(c), 1)) #define likely(c) (__builtin_expect(!!(c), 1))
#define unlikely(c) (__builtin_expect(!!(c), 0)) #define unlikely(c) (__builtin_expect(!!(c), 0))
@ -12,4 +13,16 @@
#define unlikely(c) (c) #define unlikely(c) (c)
#endif #endif
/* Round up to nearest power of two */
static inline uint32_t next_power_of_two(uint32_t v) {
/* See: https://graphics.stanford.edu/%7Eseander/bithacks.html#RoundUpPowerOf2 */
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return ++v;
}
#endif // UTIL_H #endif // UTIL_H