获取无符号整数的最大值(按位不为零) [英] Obtaining max of unsigned integer with bitwise not on zero value
问题描述
我正在尝试获取某种无符号整数类型的最大值,而不包含任何像<limits>
这样的标头.所以我想我只是将无符号整数值0的位翻转.
I'm trying to obtain the maximum value of a certain unsigned integer type without including any headers like <limits>
. So I thought I'd simply flip the bits of the unsigned integer value 0.
#include <iostream>
#include <limits>
int main()
{
std::cout << (~0U) << '\n'; // #1
std::cout << (std::numeric_limits< unsigned >::max()) << '\n'; // #2
return 0;
}
我对两者之间的细微差别不是很有经验.这就是为什么我问使用第一种方法是否可能发生某些意外行为或某些平台/体系结构问题.
I'm not very experienced on the subtle differences between these. Which is why I'm asking if some unexpected behavior or some platform/architecture issues could occur by using the first method.
推荐答案
...获取某种无符号整数类型的最大值,而不包含任何标头
... to obtain the maximum value of a certain unsigned integer type without including any headers
只需分配值-1
unsigned_type_of_choice max = -1;
将-1
(是int
)转换为任何无符号类型,会导致 number的值比最大值减去-1大.
Conversion of the -1
, which is an int
, to any unsigned type results in the value of number that is one greater than the largest value minus 1.
以下内容不提供目标类型的最大值.当目标类型范围超出unsigned
的范围(~0U
的类型)时,它将失败. @Christopher Oicles
The following does not provide the maximum value of the destination type. It fails when the destination type range exceed the range of unsigned
, which is the type of ~0U
. @Christopher Oicles
// problem
unsigned_type_of_choice max_wannabe = ~0U;
这篇关于获取无符号整数的最大值(按位不为零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!