libstdc++
bit
Go to the documentation of this file.
1// <bit> -*- C++ -*-
2
3// Copyright (C) 2018-2024 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/bit
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_BIT
30#define _GLIBCXX_BIT 1
31
32#ifdef _GLIBCXX_SYSHDR
33#pragma GCC system_header
34#endif
35
36#if __cplusplus >= 201402L
37
38#include <concepts> // for std::integral
39#include <type_traits>
40
41#if _GLIBCXX_HOSTED || __has_include(<ext/numeric_traits.h>)
42# include <ext/numeric_traits.h>
43#else
44# include <limits>
45/// @cond undocumented
46namespace __gnu_cxx
47{
48 template<typename _Tp>
49 struct __int_traits
50 {
51 static constexpr int __digits = std::numeric_limits<_Tp>::digits;
52 static constexpr _Tp __max = std::numeric_limits<_Tp>::max();
53 };
54}
55/// @endcond
56#endif
57
58#define __glibcxx_want_bit_cast
59#define __glibcxx_want_byteswap
60#define __glibcxx_want_bitops
61#define __glibcxx_want_int_pow2
62#define __glibcxx_want_endian
63#include <bits/version.h>
64
65namespace std _GLIBCXX_VISIBILITY(default)
66{
67_GLIBCXX_BEGIN_NAMESPACE_VERSION
68
69 /**
70 * @defgroup bit_manip Bit manipulation
71 * @ingroup numerics
72 *
73 * Utilities for examining and manipulating individual bits.
74 *
75 * @{
76 */
77
78#ifdef __cpp_lib_bit_cast // C++ >= 20
79
80 /// Create a value of type `To` from the bits of `from`.
81 /**
82 * @tparam _To A trivially-copyable type.
83 * @param __from A trivially-copyable object of the same size as `_To`.
84 * @return An object of type `_To`.
85 * @since C++20
86 */
87 template<typename _To, typename _From>
88 [[nodiscard]]
89 constexpr _To
90 bit_cast(const _From& __from) noexcept
91#ifdef __cpp_concepts
92 requires (sizeof(_To) == sizeof(_From))
93 && is_trivially_copyable_v<_To> && is_trivially_copyable_v<_From>
94#endif
95 {
96 return __builtin_bit_cast(_To, __from);
97 }
98#endif // __cpp_lib_bit_cast
99
100#ifdef __cpp_lib_byteswap // C++ >= 23
101
102 /// Reverse order of bytes in the object representation of `value`.
103 /**
104 * @tparam _Tp An integral type.
105 * @param __value An object of integer type.
106 * @return An object of the same type, with the bytes reversed.
107 * @since C++23
108 */
109 template<integral _Tp>
110 [[nodiscard]]
111 constexpr _Tp
112 byteswap(_Tp __value) noexcept
113 {
114 if constexpr (sizeof(_Tp) == 1)
115 return __value;
116#if __cpp_if_consteval >= 202106L && __CHAR_BIT__ == 8
117 if !consteval
118 {
119 if constexpr (sizeof(_Tp) == 2)
120 return __builtin_bswap16(__value);
121 if constexpr (sizeof(_Tp) == 4)
122 return __builtin_bswap32(__value);
123 if constexpr (sizeof(_Tp) == 8)
124 return __builtin_bswap64(__value);
125 if constexpr (sizeof(_Tp) == 16)
126#if __has_builtin(__builtin_bswap128)
127 return __builtin_bswap128(__value);
128#else
129 return (__builtin_bswap64(__value >> 64)
130 | (static_cast<_Tp>(__builtin_bswap64(__value)) << 64));
131#endif
132 }
133#endif
134
135 // Fallback implementation that handles even __int24 etc.
136 using _Up = typename __make_unsigned<__remove_cv_t<_Tp>>::__type;
137 size_t __diff = __CHAR_BIT__ * (sizeof(_Tp) - 1);
138 _Up __mask1 = static_cast<unsigned char>(~0);
139 _Up __mask2 = __mask1 << __diff;
140 _Up __val = __value;
141 for (size_t __i = 0; __i < sizeof(_Tp) / 2; ++__i)
142 {
143 _Up __byte1 = __val & __mask1;
144 _Up __byte2 = __val & __mask2;
145 __val = (__val ^ __byte1 ^ __byte2
146 ^ (__byte1 << __diff) ^ (__byte2 >> __diff));
147 __mask1 <<= __CHAR_BIT__;
148 __mask2 >>= __CHAR_BIT__;
149 __diff -= 2 * __CHAR_BIT__;
150 }
151 return __val;
152 }
153#endif // __cpp_lib_byteswap
154
155 /// @cond undocumented
156
157 template<typename _Tp>
158 constexpr _Tp
159 __rotl(_Tp __x, int __s) noexcept
160 {
161 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
162 if _GLIBCXX17_CONSTEXPR ((_Nd & (_Nd - 1)) == 0)
163 {
164 // Variant for power of two _Nd which the compiler can
165 // easily pattern match.
166 constexpr unsigned __uNd = _Nd;
167 const unsigned __r = __s;
168 return (__x << (__r % __uNd)) | (__x >> ((-__r) % __uNd));
169 }
170 const int __r = __s % _Nd;
171 if (__r == 0)
172 return __x;
173 else if (__r > 0)
174 return (__x << __r) | (__x >> ((_Nd - __r) % _Nd));
175 else
176 return (__x >> -__r) | (__x << ((_Nd + __r) % _Nd)); // rotr(x, -r)
177 }
178
179 template<typename _Tp>
180 constexpr _Tp
181 __rotr(_Tp __x, int __s) noexcept
182 {
183 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
184 if _GLIBCXX17_CONSTEXPR ((_Nd & (_Nd - 1)) == 0)
185 {
186 // Variant for power of two _Nd which the compiler can
187 // easily pattern match.
188 constexpr unsigned __uNd = _Nd;
189 const unsigned __r = __s;
190 return (__x >> (__r % __uNd)) | (__x << ((-__r) % __uNd));
191 }
192 const int __r = __s % _Nd;
193 if (__r == 0)
194 return __x;
195 else if (__r > 0)
196 return (__x >> __r) | (__x << ((_Nd - __r) % _Nd));
197 else
198 return (__x << -__r) | (__x >> ((_Nd + __r) % _Nd)); // rotl(x, -r)
199 }
200
201 template<typename _Tp>
202 constexpr int
203 __countl_zero(_Tp __x) noexcept
204 {
205 using __gnu_cxx::__int_traits;
206 constexpr auto _Nd = __int_traits<_Tp>::__digits;
207
208 if (__x == 0)
209 return _Nd;
210
211 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
212 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
213 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
214
215 if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_u)
216 {
217 constexpr int __diff = _Nd_u - _Nd;
218 return __builtin_clz(__x) - __diff;
219 }
220 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ul)
221 {
222 constexpr int __diff = _Nd_ul - _Nd;
223 return __builtin_clzl(__x) - __diff;
224 }
225 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ull)
226 {
227 constexpr int __diff = _Nd_ull - _Nd;
228 return __builtin_clzll(__x) - __diff;
229 }
230 else // (_Nd > _Nd_ull)
231 {
232 static_assert(_Nd <= (2 * _Nd_ull),
233 "Maximum supported integer size is 128-bit");
234
235 unsigned long long __high = __x >> _Nd_ull;
236 if (__high != 0)
237 {
238 constexpr int __diff = (2 * _Nd_ull) - _Nd;
239 return __builtin_clzll(__high) - __diff;
240 }
241 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
242 unsigned long long __low = __x & __max_ull;
243 return (_Nd - _Nd_ull) + __builtin_clzll(__low);
244 }
245 }
246
247 template<typename _Tp>
248 constexpr int
249 __countl_one(_Tp __x) noexcept
250 {
251 return std::__countl_zero<_Tp>((_Tp)~__x);
252 }
253
254 template<typename _Tp>
255 constexpr int
256 __countr_zero(_Tp __x) noexcept
257 {
258 using __gnu_cxx::__int_traits;
259 constexpr auto _Nd = __int_traits<_Tp>::__digits;
260
261 if (__x == 0)
262 return _Nd;
263
264 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
265 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
266 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
267
268 if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_u)
269 return __builtin_ctz(__x);
270 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ul)
271 return __builtin_ctzl(__x);
272 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ull)
273 return __builtin_ctzll(__x);
274 else // (_Nd > _Nd_ull)
275 {
276 static_assert(_Nd <= (2 * _Nd_ull),
277 "Maximum supported integer size is 128-bit");
278
279 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
280 unsigned long long __low = __x & __max_ull;
281 if (__low != 0)
282 return __builtin_ctzll(__low);
283 unsigned long long __high = __x >> _Nd_ull;
284 return __builtin_ctzll(__high) + _Nd_ull;
285 }
286 }
287
288 template<typename _Tp>
289 constexpr int
290 __countr_one(_Tp __x) noexcept
291 {
292 return std::__countr_zero((_Tp)~__x);
293 }
294
295 template<typename _Tp>
296 constexpr int
297 __popcount(_Tp __x) noexcept
298 {
299 using __gnu_cxx::__int_traits;
300 constexpr auto _Nd = __int_traits<_Tp>::__digits;
301
302 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
303 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
304 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
305
306 if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_u)
307 return __builtin_popcount(__x);
308 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ul)
309 return __builtin_popcountl(__x);
310 else if _GLIBCXX17_CONSTEXPR (_Nd <= _Nd_ull)
311 return __builtin_popcountll(__x);
312 else // (_Nd > _Nd_ull)
313 {
314 static_assert(_Nd <= (2 * _Nd_ull),
315 "Maximum supported integer size is 128-bit");
316
317 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
318 unsigned long long __low = __x & __max_ull;
319 unsigned long long __high = __x >> _Nd_ull;
320 return __builtin_popcountll(__low) + __builtin_popcountll(__high);
321 }
322 }
323
324 template<typename _Tp>
325 constexpr bool
326 __has_single_bit(_Tp __x) noexcept
327 { return std::__popcount(__x) == 1; }
328
329 template<typename _Tp>
330 constexpr _Tp
331 __bit_ceil(_Tp __x) noexcept
332 {
333 using __gnu_cxx::__int_traits;
334 constexpr auto _Nd = __int_traits<_Tp>::__digits;
335 if (__x == 0 || __x == 1)
336 return 1;
337 auto __shift_exponent = _Nd - std::__countl_zero((_Tp)(__x - 1u));
338 // If the shift exponent equals _Nd then the correct result is not
339 // representable as a value of _Tp, and so the result is undefined.
340 // Want that undefined behaviour to be detected in constant expressions,
341 // by UBSan, and by debug assertions.
342 if (!std::__is_constant_evaluated())
343 {
344 __glibcxx_assert( __shift_exponent != __int_traits<_Tp>::__digits );
345 }
346
347 using __promoted_type = decltype(__x << 1);
348 if _GLIBCXX17_CONSTEXPR (!is_same<__promoted_type, _Tp>::value)
349 {
350 // If __x undergoes integral promotion then shifting by _Nd is
351 // not undefined. In order to make the shift undefined, so that
352 // it is diagnosed in constant expressions and by UBsan, we also
353 // need to "promote" the shift exponent to be too large for the
354 // promoted type.
355 const int __extra_exp = sizeof(__promoted_type) / sizeof(_Tp) / 2;
356 __shift_exponent |= (__shift_exponent & _Nd) << __extra_exp;
357 }
358 return (_Tp)1u << __shift_exponent;
359 }
360
361 template<typename _Tp>
362 constexpr _Tp
363 __bit_floor(_Tp __x) noexcept
364 {
365 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
366 if (__x == 0)
367 return 0;
368 return (_Tp)1u << (_Nd - std::__countl_zero((_Tp)(__x >> 1)));
369 }
370
371 template<typename _Tp>
372 constexpr int
373 __bit_width(_Tp __x) noexcept
374 {
375 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
376 return _Nd - std::__countl_zero(__x);
377 }
378
379 /// @endcond
380
381#ifdef __cpp_lib_bitops // C++ >= 20
382
383 /// @cond undocumented
384 template<typename _Tp>
385 concept __unsigned_integer = __is_unsigned_integer<_Tp>::value;
386 /// @endcond
387
388 // [bit.rot], rotating
389
390 /// Rotate `x` to the left by `s` bits.
391 template<__unsigned_integer _Tp>
392 [[nodiscard]] constexpr _Tp
393 rotl(_Tp __x, int __s) noexcept
394 { return std::__rotl(__x, __s); }
395
396 /// Rotate `x` to the right by `s` bits.
397 template<__unsigned_integer _Tp>
398 [[nodiscard]] constexpr _Tp
399 rotr(_Tp __x, int __s) noexcept
400 { return std::__rotr(__x, __s); }
401
402 // [bit.count], counting
403
404 /// The number of contiguous zero bits, starting from the highest bit.
405 template<__unsigned_integer _Tp>
406 constexpr int
407 countl_zero(_Tp __x) noexcept
408 { return std::__countl_zero(__x); }
409
410 /// The number of contiguous one bits, starting from the highest bit.
411 template<__unsigned_integer _Tp>
412 constexpr int
413 countl_one(_Tp __x) noexcept
414 { return std::__countl_one(__x); }
415
416 /// The number of contiguous zero bits, starting from the lowest bit.
417 template<__unsigned_integer _Tp>
418 constexpr int
419 countr_zero(_Tp __x) noexcept
420 { return std::__countr_zero(__x); }
421
422 /// The number of contiguous one bits, starting from the lowest bit.
423 template<__unsigned_integer _Tp>
424 constexpr int
425 countr_one(_Tp __x) noexcept
426 { return std::__countr_one(__x); }
427
428 /// The number of bits set in `x`.
429 template<__unsigned_integer _Tp>
430 constexpr int
431 popcount(_Tp __x) noexcept
432 { return std::__popcount(__x); }
433#endif // __cpp_lib_bitops
434
435#ifdef __cpp_lib_int_pow2 // C++ >= 20
436 // [bit.pow.two], integral powers of 2
437
438 /// True if `x` is a power of two, false otherwise.
439 template<__unsigned_integer _Tp>
440 constexpr bool
441 has_single_bit(_Tp __x) noexcept
442 { return std::__has_single_bit(__x); }
443
444 /// The smallest power-of-two not less than `x`.
445 template<__unsigned_integer _Tp>
446 constexpr _Tp
447 bit_ceil(_Tp __x) noexcept
448 { return std::__bit_ceil(__x); }
449
450 /// The largest power-of-two not greater than `x`.
451 template<__unsigned_integer _Tp>
452 constexpr _Tp
453 bit_floor(_Tp __x) noexcept
454 { return std::__bit_floor(__x); }
455
456 // _GLIBCXX_RESOLVE_LIB_DEFECTS
457 // 3656. Inconsistent bit operations returning a count
458 /// The smallest integer greater than the base-2 logarithm of `x`.
459 template<__unsigned_integer _Tp>
460 constexpr int
461 bit_width(_Tp __x) noexcept
462 { return std::__bit_width(__x); }
463#endif // defined (__cpp_lib_int_pow2)
464
465#ifdef __cpp_lib_endian // C++ >= 20
466
467 /// Byte order constants
468 /**
469 * The platform endianness can be checked by comparing `std::endian::native`
470 * to one of `std::endian::big` or `std::endian::little`.
471 *
472 * @since C++20
473 */
474 enum class endian
475 {
476 little = __ORDER_LITTLE_ENDIAN__,
477 big = __ORDER_BIG_ENDIAN__,
478 native = __BYTE_ORDER__
479 };
480#endif // __cpp_lib_endian
481
482 /// @}
483
484_GLIBCXX_END_NAMESPACE_VERSION
485} // namespace std
486
487#endif // C++14
488#endif // _GLIBCXX_BIT