xref: /freebsd/lib/libc/stdbit/stdc_bit_floor.c (revision 6296500a85c8474e3ff3fe2f8e4a9d56dd0acd64)
1 /*
2  * Copyright (c) 2025 Robert Clausecker <fuz@FreeBSD.org>
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6 
7 #include <limits.h>
8 #include <stdbit.h>
9 
10 unsigned char
stdc_bit_floor_uc(unsigned char x)11 stdc_bit_floor_uc(unsigned char x)
12 {
13 	if (x == 0)
14 		return (0);
15 
16 	return (1U << (UINT_WIDTH - __builtin_clz(x) - 1));
17 }
18 
19 unsigned short
stdc_bit_floor_us(unsigned short x)20 stdc_bit_floor_us(unsigned short x)
21 {
22 	if (x == 0)
23 		return (0);
24 
25 	return (1U << (UINT_WIDTH - __builtin_clz(x) - 1));
26 }
27 
28 unsigned int
stdc_bit_floor_ui(unsigned int x)29 stdc_bit_floor_ui(unsigned int x)
30 {
31 	if (x == 0)
32 		return (0);
33 
34 	return (1U << (UINT_WIDTH - __builtin_clz(x) - 1));
35 }
36 
37 unsigned long
stdc_bit_floor_ul(unsigned long x)38 stdc_bit_floor_ul(unsigned long x)
39 {
40 	if (x == 0)
41 		return (0);
42 
43 	return (1UL << (ULONG_WIDTH - __builtin_clzl(x) - 1));
44 }
45 
46 unsigned long long
stdc_bit_floor_ull(unsigned long long x)47 stdc_bit_floor_ull(unsigned long long x)
48 {
49 	if (x == 0)
50 		return (0);
51 
52 	return (1ULL << (ULLONG_WIDTH - __builtin_clzll(x) - 1));
53 }
54