std::bit_floor(3)
π std::bit_floor(3) β C++ Standard Libary π
β¨ NAME β¨
std::bit_floor β literally std::bit_floor, bestie. We're in the C++ Standard Libary manual, section 3, and this page is all about that one function π
πΈ Synopsis πΈ
Defined in header <bit>:
template< class T > (since C++20)
constexpr T bit_floor( T x ) noexcept;
If x is not zero, calculates the largest integral power of two that is not greater than x. If x is zero, returns zero. No cap, that's the whole vibe π«Ά
This overload participates in overload resolution only if T is an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type).
π¦ Parameters π¦
xβ unsigned integer value. That's the number getting thebit_floortreatment, bestie β¨
π Return value π
Zero if x is zero; otherwise, the largest integral power of two that is not greater than x. Periodt π
π Notes π
Feature-test macro check, because we love a paper trail:
__cpp_lib_int_pow2β value202002L, standard(C++20), feature: integral power-of-2 operations.
π Possible implementation π
Here's one possible implementation, and yes it's giving "I know bit_width" energy:
template<std::unsigned_integral T>
requires !std::same_as<T, bool> && !std::same_as<T, char> &&
!std::same_as<T, char8_t> && !std::same_as<T, char16_t>
&&
!std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr T bit_floor(T x) noexcept
{
if (x != 0)
return T{1} << (std::bit_width(x) - 1);
return 0;
}
π Example π
// Run this code β yes bestie, hit run:
#include <bit>
#include <bitset>
#include <iostream>
int main()
{
using bin = std::bitset<8>;
for (unsigned x = 0; x != 10; ++x)
{
auto const z = std::bit_floor(x); // `floor2` before P1956R1
std::cout << "bit_floor( " << bin(x) << " ) = " << bin(z) <<
'\n';
}
}
π Output π
bit_floor( 00000000 ) = 00000000
bit_floor( 00000001 ) = 00000001
bit_floor( 00000010 ) = 00000010
bit_floor( 00000011 ) = 00000010
bit_floor( 00000100 ) = 00000100
bit_floor( 00000101 ) = 00000100
bit_floor( 00000110 ) = 00000100
bit_floor( 00000111 ) = 00000100
bit_floor( 00001000 ) = 00001000
bit_floor( 00001001 ) = 00001000
π§ See also π§
bit_ceilβ finds the smallest integral power of two not less than the given value(C++20)(function template)rotrβ computes the result of bitwise right-rotation(C++20)(function template)bit_widthβ finds the smallest number of bits needed to represent the given value(C++20)(function template)has_single_bitβ checks if a number is an integral power of 2(C++20)(function template)
βΏ okay that's the page, bestie β source: http://cppreference.com, version/date: 2024.06.10, page: std::bit_floor(3). mwah πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms