Path: blob/main/lib/libc/stdbit/stdc_leading_ones.c
96290 views
/*1* Copyright (c) 2025 Robert Clausecker <[email protected]>2*3* SPDX-License-Identifier: BSD-2-Clause4*/56#include <assert.h>7#include <limits.h>8#include <stdbit.h>910/* Avoid triggering undefined behavior if x == 0. */11static_assert(UCHAR_WIDTH < UINT_WIDTH,12"stdc_leading_ones_uc needs UCHAR_WIDTH < UINT_WIDTH");1314unsigned int15stdc_leading_ones_uc(unsigned char x)16{17const int offset = UINT_WIDTH - UCHAR_WIDTH;1819return (__builtin_clz(~(x << offset)));20}2122/* Avoid triggering undefined behavior if x == 0. */23static_assert(USHRT_WIDTH < UINT_WIDTH,24"stdc_leading_ones_us needs USHRT_WIDTH < UINT_WIDTH");2526unsigned int27stdc_leading_ones_us(unsigned short x)28{29const int offset = UINT_WIDTH - USHRT_WIDTH;3031return (__builtin_clz(~(x << offset)));32}3334unsigned int35stdc_leading_ones_ui(unsigned int x)36{37if (x == ~0U)38return (UINT_WIDTH);3940return (__builtin_clz(~x));41}4243unsigned int44stdc_leading_ones_ul(unsigned long x)45{46if (x == ~0UL)47return (ULONG_WIDTH);4849return (__builtin_clzl(~x));50}5152unsigned int53stdc_leading_ones_ull(unsigned long long x)54{55if (x == ~0ULL)56return (ULLONG_WIDTH);5758return (__builtin_clzll(~x));59}606162