简体   繁体   English

使用按位而不是零值获取无符号整数的最大值

[英]Obtaining max of unsigned integer with bitwise not on zero value

I'm trying to obtain the maximum value of a certain unsigned integer type without including any headers like <limits> . 我试图获取某个无符号整数类型的最大值,而不包括像<limits>这样的任何头。 So I thought I'd simply flip the bits of the unsigned integer value 0. 所以我想我只是翻转无符号整数值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 ...获取某个无符号整数类型的最大值而不包括任何头

Simply assign the value -1 只需指定值-1

unsigned_type_of_choice max = -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. -1 (即int )转换为任何无符号类型会导致number的值比最大值减1 更大

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 . 当目标类型范围超出unsigned范围时,它会失败,这是~0U的类型。 @Christopher Oicles @Christopher Oicles

// problem
unsigned_type_of_choice max_wannabe = ~0U;

You shouldn't assign ~0U to just any unsigned type, chux's answer already explains why. 您不应该将~0U分配给任何无符号类型, chux的答案已经解释了原因。

For C++, with the following you can get the maximum possible value for all unsigned types. 对于C ++,使用以下内容可以获得所有无符号类型的最大可能值。

template <typename T>
T max_for_unsigned_type() {
    return ~(static_cast<T> (0));
}

You are negating a zero of your exact type . 你正在否定你的确切类型的零 I use a verbose function name because it shouldn't be used for signed values. 我使用详细的函数名称,因为它不应该用于签名值。 The problem is that for checking signedness the easiest way would be including an extra header, namely type_traits . 问题是,对于检查签名,最简单的方法是包括一个额外的头,即type_traits This other answer then would be useful. 那么这个其他答案将是有用的。

Usage: 用法:

max_for_unsigned_type<uint8_t> ();
max_for_unsigned_type<uint16_t> ();
max_for_unsigned_type<uint32_t> ();
max_for_unsigned_type<uint64_t> ();
max_for_unsigned_type<unsigned> ();

Values returned: (see test code here ) 返回值:(请参阅此处的测试代码)

255
65535
4294967295
18446744073709551615
4294967295

Note: Doing it for signed types is much more difficult, see Programmatically determining max value of a signed integer type . 注意:对签名类型执行此操作要困难得多,请参阅以编程方式确定有符号整数类型的最大值

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

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