static_cast< T>(-1)是生成无数字限制的全一位数据的正确方法吗? [英] Is static_cast<T>(-1) the right way to generate all-one-bits data without numeric_limits?
问题描述
我正在无法访问C ++标准库(特别是不能访问std::numeric_limits
)的环境中编写C ++代码.假设我要实现
I'm writing C++ code in an environment in which I don't have access to the C++ standard library, specifically not to std::numeric_limits
. Suppose I want to implement
template <typename T> constexpr T all_ones( /* ... */ )
重点放在无符号整数类型上,我该放在哪里?具体来说,static_cast<T>(-1)
是否足够好? (我猜其他类型可以根据其大小将其视为无符号字符数组.)
Focusing on unsigned integral types, what do I put there? Specifically, is static_cast<T>(-1)
good enough? (Other types I could treat as an array of unsigned chars based on their size I guess.)
推荐答案
在0
上使用bitwise NOT
运算符~
.
T allOnes = ~(T)0;
A static_cast<T>(-1)
采用二进制补码,这是不可移植的.如果您只关心未签名的类型,那么 hvd的答案是可行的方法.
A static_cast<T>(-1)
assumes two's complement, which is not portable. If you are only concerned about unsigned types, hvd's answer is the way to go.
工作示例: https://ideone.com/iV28u0
这篇关于static_cast< T>(-1)是生成无数字限制的全一位数据的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!