libstdc++
bit
Go to the documentation of this file.
1// <bit> -*- C++ -*-
2
3// Copyright (C) 2018-2026 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 >= 201103L
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#pragma GCC diagnostic push
157#pragma GCC diagnostic ignored "-Wc++17-extensions" // if constexpr
158
159 template<typename _Tp>
160 _GLIBCXX14_CONSTEXPR _Tp
161 __rotl(_Tp __x, int __s) noexcept
162 {
163 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
164 if constexpr ((_Nd & (_Nd - 1)) == 0)
165 {
166 // Variant for power of two _Nd which the compiler can
167 // easily pattern match.
168 constexpr unsigned __uNd = _Nd;
169 const auto __r = static_cast<unsigned>(__s);
170 return (__x << (__r % __uNd)) | (__x >> ((-__r) % __uNd));
171 }
172 const int __r = __s % _Nd;
173 if (__r == 0)
174 return __x;
175 else if (__r > 0)
176 return (__x << __r) | (__x >> ((_Nd - __r) % _Nd));
177 else
178 return (__x >> -__r) | (__x << ((_Nd + __r) % _Nd)); // rotr(x, -r)
179 }
180
181 template<typename _Tp>
182 _GLIBCXX14_CONSTEXPR _Tp
183 __rotr(_Tp __x, int __s) noexcept
184 {
185 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
186 if constexpr ((_Nd & (_Nd - 1)) == 0)
187 {
188 // Variant for power of two _Nd which the compiler can
189 // easily pattern match.
190 constexpr unsigned __uNd = _Nd;
191 const auto __r = static_cast<unsigned>(__s);
192 return (__x >> (__r % __uNd)) | (__x << ((-__r) % __uNd));
193 }
194 const int __r = __s % _Nd;
195 if (__r == 0)
196 return __x;
197 else if (__r > 0)
198 return (__x >> __r) | (__x << ((_Nd - __r) % _Nd));
199 else
200 return (__x << -__r) | (__x >> ((_Nd + __r) % _Nd)); // rotl(x, -r)
201 }
202
203#if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_clzg)
204 template<typename _Tp>
205 constexpr int
206 __countl_zero(_Tp __x) noexcept
207 {
208 return __builtin_clzg(__x, __gnu_cxx::__int_traits<_Tp>::__digits);
209 }
210#else
211 template<typename _Tp>
212 _GLIBCXX14_CONSTEXPR int
213 __countl_zero(_Tp __x) noexcept
214 {
216 constexpr auto _Nd = __int_traits<_Tp>::__digits;
217 if (__x == 0)
218 return _Nd;
219
220 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
221 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
222 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
223
224 if constexpr (_Nd <= _Nd_u)
225 {
226 constexpr int __diff = _Nd_u - _Nd;
227 return __builtin_clz(__x) - __diff;
228 }
229 else if constexpr (_Nd <= _Nd_ul)
230 {
231 constexpr int __diff = _Nd_ul - _Nd;
232 return __builtin_clzl(__x) - __diff;
233 }
234 else if constexpr (_Nd <= _Nd_ull)
235 {
236 constexpr int __diff = _Nd_ull - _Nd;
237 return __builtin_clzll(__x) - __diff;
238 }
239 else // (_Nd > _Nd_ull)
240 {
241 static_assert(_Nd <= (2 * _Nd_ull),
242 "Maximum supported integer size is 128-bit");
243
244 unsigned long long __high = __x >> _Nd_ull;
245 if (__high != 0)
246 {
247 constexpr int __diff = (2 * _Nd_ull) - _Nd;
248 return __builtin_clzll(__high) - __diff;
249 }
250 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
251 unsigned long long __low = __x & __max_ull;
252 return (_Nd - _Nd_ull) + __builtin_clzll(__low);
253 }
254 }
255#endif
256
257 template<typename _Tp>
258 constexpr int
259 __countl_one(_Tp __x) noexcept
260 {
261 return std::__countl_zero<_Tp>((_Tp)~__x);
262 }
263
264#if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_ctzg)
265 template<typename _Tp>
266 constexpr int
267 __countr_zero(_Tp __x) noexcept
268 {
269 return __builtin_ctzg(__x, __gnu_cxx::__int_traits<_Tp>::__digits);
270 }
271#else
272 template<typename _Tp>
273 _GLIBCXX14_CONSTEXPR int
274 __countr_zero(_Tp __x) noexcept
275 {
277 constexpr auto _Nd = __int_traits<_Tp>::__digits;
278 if (__x == 0)
279 return _Nd;
280
281 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
282 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
283 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
284
285 if constexpr (_Nd <= _Nd_u)
286 return __builtin_ctz(__x);
287 else if constexpr (_Nd <= _Nd_ul)
288 return __builtin_ctzl(__x);
289 else if constexpr (_Nd <= _Nd_ull)
290 return __builtin_ctzll(__x);
291 else // (_Nd > _Nd_ull)
292 {
293 static_assert(_Nd <= (2 * _Nd_ull),
294 "Maximum supported integer size is 128-bit");
295
296 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
297 unsigned long long __low = __x & __max_ull;
298 if (__low != 0)
299 return __builtin_ctzll(__low);
300 unsigned long long __high = __x >> _Nd_ull;
301 return __builtin_ctzll(__high) + _Nd_ull;
302 }
303 }
304#endif
305
306 template<typename _Tp>
307 constexpr int
308 __countr_one(_Tp __x) noexcept
309 {
310 return std::__countr_zero((_Tp)~__x);
311 }
312
313#if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_popcountg)
314 template<typename _Tp>
315 constexpr int
316 __popcount(_Tp __x) noexcept
317 {
318 return __builtin_popcountg(__x);
319 }
320#else
321 template<typename _Tp>
322 _GLIBCXX14_CONSTEXPR int
323 __popcount(_Tp __x) noexcept
324 {
326 constexpr auto _Nd = __int_traits<_Tp>::__digits;
327
328 constexpr auto _Nd_ull = __int_traits<unsigned long long>::__digits;
329 constexpr auto _Nd_ul = __int_traits<unsigned long>::__digits;
330 constexpr auto _Nd_u = __int_traits<unsigned>::__digits;
331
332 if constexpr (_Nd <= _Nd_u)
333 return __builtin_popcount(__x);
334 else if constexpr (_Nd <= _Nd_ul)
335 return __builtin_popcountl(__x);
336 else if constexpr (_Nd <= _Nd_ull)
337 return __builtin_popcountll(__x);
338 else // (_Nd > _Nd_ull)
339 {
340 static_assert(_Nd <= (2 * _Nd_ull),
341 "Maximum supported integer size is 128-bit");
342
343 constexpr auto __max_ull = __int_traits<unsigned long long>::__max;
344 unsigned long long __low = __x & __max_ull;
345 unsigned long long __high = __x >> _Nd_ull;
346 return __builtin_popcountll(__low) + __builtin_popcountll(__high);
347 }
348 }
349#endif
350
351 template<typename _Tp>
352 constexpr bool
353 __has_single_bit(_Tp __x) noexcept
354 { return std::__popcount(__x) == 1; }
355
356 template<typename _Tp>
357 constexpr int
358 __bit_width(_Tp __x) noexcept
359 {
360 return __gnu_cxx::__int_traits<_Tp>::__digits - std::__countl_zero(__x);
361 }
362
363 template<typename _Tp>
364 constexpr _Tp
365 __bit_floor(_Tp __x) noexcept
366 {
367 return (__x == 0) ? (_Tp)0 : ((_Tp)1u << (std::__bit_width(__x) - 1));
368 }
369
370 template<typename _Tp>
371 _GLIBCXX14_CONSTEXPR _Tp
372 __bit_ceil(_Tp __x) noexcept
373 {
375 constexpr auto _Nd = __int_traits<_Tp>::__digits;
376 if (__x == 0 || __x == 1)
377 return 1;
378 auto __shift_exponent = _Nd - std::__countl_zero((_Tp)(__x - 1u));
379 // If the shift exponent equals _Nd then the correct result is not
380 // representable as a value of _Tp, and so the result is undefined.
381 // Want that undefined behaviour to be detected in constant expressions,
382 // by UBSan, and by debug assertions.
383 if (!std::__is_constant_evaluated())
384 {
385 __glibcxx_assert( __shift_exponent != __int_traits<_Tp>::__digits );
386 }
387
388 using __promoted_type = decltype(__x << 1);
390 {
391 // If __x undergoes integral promotion then shifting by _Nd is
392 // not undefined. In order to make the shift undefined, so that
393 // it is diagnosed in constant expressions and by UBsan, we also
394 // need to "promote" the shift exponent to be too large for the
395 // promoted type.
396 const int __extra_exp = sizeof(__promoted_type) / sizeof(_Tp) / 2;
397 __shift_exponent |= (__shift_exponent & _Nd) << __extra_exp;
398 }
399 return (_Tp)1u << __shift_exponent;
400 }
401
402#pragma GCC diagnostic pop
403 /// @endcond
404
405#ifdef __cpp_lib_bitops // C++ >= 20
406
407 /// @cond undocumented
408 template<typename _Tp>
409 concept __unsigned_integer = __is_unsigned_integer<_Tp>::value;
410 /// @endcond
411
412 // [bit.rot], rotating
413
414 /// Rotate `x` to the left by `s` bits.
415 template<__unsigned_integer _Tp>
416 [[nodiscard]] constexpr _Tp
417 rotl(_Tp __x, int __s) noexcept
418 { return std::__rotl(__x, __s); }
419
420 /// Rotate `x` to the right by `s` bits.
421 template<__unsigned_integer _Tp>
422 [[nodiscard]] constexpr _Tp
423 rotr(_Tp __x, int __s) noexcept
424 { return std::__rotr(__x, __s); }
425
426 // [bit.count], counting
427
428 /// The number of contiguous zero bits, starting from the highest bit.
429 template<__unsigned_integer _Tp>
430 constexpr int
431 countl_zero(_Tp __x) noexcept
432 { return std::__countl_zero(__x); }
433
434 /// The number of contiguous one bits, starting from the highest bit.
435 template<__unsigned_integer _Tp>
436 constexpr int
437 countl_one(_Tp __x) noexcept
438 { return std::__countl_one(__x); }
439
440 /// The number of contiguous zero bits, starting from the lowest bit.
441 template<__unsigned_integer _Tp>
442 constexpr int
443 countr_zero(_Tp __x) noexcept
444 { return std::__countr_zero(__x); }
445
446 /// The number of contiguous one bits, starting from the lowest bit.
447 template<__unsigned_integer _Tp>
448 constexpr int
449 countr_one(_Tp __x) noexcept
450 { return std::__countr_one(__x); }
451
452 /// The number of bits set in `x`.
453 template<__unsigned_integer _Tp>
454 constexpr int
455 popcount(_Tp __x) noexcept
456 { return std::__popcount(__x); }
457#endif // __cpp_lib_bitops
458
459#ifdef __cpp_lib_int_pow2 // C++ >= 20
460 // [bit.pow.two], integral powers of 2
461
462 /// True if `x` is a power of two, false otherwise.
463 template<__unsigned_integer _Tp>
464 constexpr bool
465 has_single_bit(_Tp __x) noexcept
466 { return std::__has_single_bit(__x); }
467
468 /// The smallest power-of-two not less than `x`.
469 template<__unsigned_integer _Tp>
470 constexpr _Tp
471 bit_ceil(_Tp __x) noexcept
472 { return std::__bit_ceil(__x); }
473
474 /// The largest power-of-two not greater than `x`.
475 template<__unsigned_integer _Tp>
476 constexpr _Tp
477 bit_floor(_Tp __x) noexcept
478 { return std::__bit_floor(__x); }
479
480 // _GLIBCXX_RESOLVE_LIB_DEFECTS
481 // 3656. Inconsistent bit operations returning a count
482 /// The smallest integer greater than the base-2 logarithm of `x`.
483 template<__unsigned_integer _Tp>
484 constexpr int
485 bit_width(_Tp __x) noexcept
486 { return std::__bit_width(__x); }
487#endif // defined (__cpp_lib_int_pow2)
488
489#ifdef __cpp_lib_endian // C++ >= 20
490
491 /// Byte order constants
492 /**
493 * The platform endianness can be checked by comparing `std::endian::native`
494 * to one of `std::endian::big` or `std::endian::little`.
495 *
496 * @since C++20
497 */
498 enum class endian
499 {
500 little = __ORDER_LITTLE_ENDIAN__,
501 big = __ORDER_BIG_ENDIAN__,
502 native = __BYTE_ORDER__
503 };
504#endif // __cpp_lib_endian
505
506 /// @}
507
508_GLIBCXX_END_NAMESPACE_VERSION
509} // namespace std
510
511#endif // C++11
512#endif // _GLIBCXX_BIT
ISO C++ entities toplevel namespace is std.
GNU extensions for public use.
__numeric_traits_integer< _Tp > __int_traits
Convenience alias for __numeric_traits<integer-type>.
static constexpr int digits
Definition limits:224
static constexpr _Tp max() noexcept
Definition limits:336