diff options
Diffstat (limited to 'include/c/bit/clz.h')
-rw-r--r-- | include/c/bit/clz.h | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/include/c/bit/clz.h b/include/c/bit/clz.h new file mode 100644 index 0000000..ee217f1 --- /dev/null +++ b/include/c/bit/clz.h @@ -0,0 +1,37 @@ +// Copyright 2023 Alejandro Colomar <alx@kernel.org> +// SPDX-License-Identifier: LGPL-3.0-or-later WITH LGPL-3.0-linking-exception + + +#ifndef INCLUDE_C_BIT_CLZ_H_ +#define INCLUDE_C_BIT_CLZ_H_ + + +#include <assert.h> +#include <stdint.h> + + +#pragma clang assume_nonnull begin +inline int c_leading_zeros_32(uint32_t x); +inline int c_leading_zeros_64(uint64_t x); + + +inline int +c_leading_zeros_32(uint32_t x) +{ + static_assert(sizeof(int) == sizeof(uint32_t)); + + return (x == 0) ? UINT32_WIDTH : __builtin_clz(x); +} + + +inline int +c_leading_zeros_64(uint64_t x) +{ + static_assert(sizeof(long) == sizeof(uint64_t)); + + return (x == 0) ? UINT64_WIDTH : __builtin_clzl(x); +} +#pragma clang assume_nonnull end + + +#endif // Header guard |