STDC_BIT_CEIL(3C) Standard C Library Functions STDC_BIT_CEIL(3C)

stdc_bit_ceil, stdc_bit_ceil_uc, stdc_bit_ceil_us, stdc_bit_ceil_ui, stdc_bit_ceil_ul, stdc_bit_ceil_ullfind smallest power of 2 not less than value

Standard C Library (libc, -lc)

#include <stdbit.h>

generic_value_type
stdc_bit_ceil(generic_value_type value);

unsigned char
stdc_bit_ceil_uc(unsigned char value);

unsigned short
stdc_bit_ceil_us(unsigned short value);

unsigned int
stdc_bit_ceil_ui(unsigned int value);

unsigned long
stdc_bit_ceil_ul(unsigned long value);

unsigned long long
stdc_bit_ceil_ull(unsigned long long value);

The () family of functions finds the smallest power of 2 that is not less than value. If the resulting value would not fit in the type, then 0 is returned. For example, if one were to use UINT8_MAX with () the next power of two would be 0x100, which is larger than would fit in an 8-bit unsigned char, resulting in 0.

The () function is generic and will operate on all 8, 16, 32, and 64-bit unsigned integers; however, it is only available in C23. The other functions all operate on a specific integer type, but otherwise behave the same and are available regardless of the C language version.

The functions in the stdc_bit_ceil() family returns the smallest power of 2 that is not less than value. These functions cannot fail.

Printing the bit ceiling of an integer.

#include <stdbit.h>
#include <stdio.h>
#include <limits.h>

int
main(void)
{
	printf("0x%x 0x%x 0x%x 0x%llx\n",
	    stdc_bit_ceil_uc(0xd2),
	    stdc_bit_ceil_us(0x7777),
	    stdc_bit_ceil_ui(0x038fa0ff),
	    stdc_bit_ceil_ull(0));
	return (0);
}

When compiled and run, this produces:

$ ./a.out
0x0 0x8000 0x4000000 0x1

stdc_bit_floor(3C), stdc_bit_width(3C), stdc_count_ones(3C), stdc_count_zero(3C), stdc_first_leading_one(3C), stdc_first_leading_zero(3C), stdc_first_trailing_one(3C), stdc_first_trailing_zero(3C), stdc_has_single_bit(3C), stdc_leading_ones(3C), stdc_leading_zeros(3C), stdc_trailing_ones(3C), stdc_trailing_zeros(3C), stdbit.h(3HEAD)

October 27, 2024 OmniOS