简体   繁体   English

创建编译时常量并设置前 N 位

[英]Create compile-time constants with first N bits set

In C++17, is there are way to generate at compile-time a constant with the first N bits set?在 C++17 中,有没有办法在编译时生成一个设置了前 N 位的常量?

In pseudocode, I am looking for something like:在伪代码中,我正在寻找类似的东西:

constexpr uint32_t MY_CONSTANT = setBits<2>();

Would be equivalent to:相当于:

constexpr uint32_t MY_CONSTANT = 0b11;

In other words, given a compile-time constant N, return a compile-time constant M where bits 0 to (N-1) are 1 (set).换句话说,给定一个编译时常量 N,返回一个编译时常量 M,其中位 0 到 (N-1) 为 1(设置)。

I don't think there's a ready made function for it in the standard library (although std::bitset::set is constexpr since C++23).我认为标准库中没有现成的函数(尽管std::bitset::set从 C++23 开始就是constexpr )。 You could make your own though:你可以自己制作:

template<class T, std::size_t N>
constexpr T setBits() {
    if constexpr (N == sizeof(unsigned long long) * CHAR_BIT) return ~T{};
    else return static_cast<T>((1ull << N) - 1);
}

constexpr auto MY_CONSTANT = setBits<std::uint32_t, 2>();

Example for setBits<std::uint8_t, 2>() : setBits<std::uint8_t, 2>()示例:

   0b00000001
<<          2
-------------
=  0b00000100

   0b00000100
-           1
-------------
=  0b00000011

Or negate 0 to get all bits set and right shift away all but N bits:或否定0以设置所有位并右移除N位以外的所有位:

template<class T, std::size_t N>
constexpr T setBits() {
    if constexpr (N == 0) return 0;
    else return ~T{} >> (sizeof(T) * CHAR_BIT - N);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM