gpt4 book ai didi

c++ - 如何在广义 inttype 上设置/检查 msb?

转载 作者:行者123 更新时间:2023-11-28 01:24:33 25 4
gpt4 key购买 nike

我当前的代码库中有以下代码片段:

// uint32_t id; defined somewhere
bool msb_set = id & 0x80000000

并希望将其更改为更灵活的内容:

using id_t = uint64_t;
id_t id;
bool msb_set = id & 0x80000000 // uh-oh, semantic change for any other differently sized inttype

如何根据我使用的具体 inttype 最轻松地生成适当的文字?我正在寻找

numeric_constants<id_t>::int_with_msb_set();

最佳答案

这是一个返回您想要的掩码的函数:

template<typename T>
constexpr T getMsbMask()
{
if constexpr (std::is_unsigned_v<T>)
return T(-1) - T(-1) / 2;
else
return std::numeric_limits<T>::min();
// Unsigned branch computes 0b11111... - 0b01111...
// Signed branch assumes two's complement, which will soon be the standard:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0907r0.html
}

Demo and tests on godbolt .

编译器显然可以在编译时计算出这些常量值,因此不会有任何速度损失。

另一个明显的解决方案就是为每种类型专门化的结构(类似于 std::numeric_limits)。

关于c++ - 如何在广义 inttype 上设置/检查 msb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com