data-structures-c
Loading...
Searching...
No Matches
round_up_pow2.h
Go to the documentation of this file.
1/* round_up_pow2.h
2 *
3 * Copyright (C) 2023 abxh
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 * See the file LICENSE included with this distribution for more
10 * information. */
11
21#pragma once
22
23#include <assert.h>
24#include <stdbool.h>
25#include <stddef.h>
26#include <stdint.h>
27
39static inline uint32_t round_up_pow2_32(uint32_t x)
40{
41 assert(0 < x && x <= UINT32_MAX / 2 + 1);
42
43// Test for GCC >= 3.4.0
44#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && (__GNUC_MINOR__ > 4 || __GNUC_MINOR__ == 4)))
45
46 return x == 1U ? 1U : 1U << (32 - __builtin_clz(x - 1U));
47
48#else
49 x--;
50 x |= x >> 1;
51 x |= x >> 2;
52 x |= x >> 4;
53 x |= x >> 8;
54 x |= x >> 16;
55 x++;
56 return x;
57#endif
58}
59
60// vim: ft=c
static uint32_t round_up_pow2_32(uint32_t x)
Definition round_up_pow2.h:39