获取按位不为零的无符号整数的最大值

Obtaining max of unsigned integer with bitwise not on zero value

我正在尝试获取某个无符号整数类型的最大值,但不包括任何 headers,如 <limits>。所以我想我会简单地翻转无符号整数值 0 的位。

#include <iostream>
#include <limits>

int main()
{
    std::cout << (~0U) << '\n'; // #1
    std::cout << (std::numeric_limits< unsigned >::max()) << '\n'; // #2
    return 0;
}

我对它们之间的细微差别不是很了解。这就是为什么我要问使用第一种方法是否会出现一些意外行为或一些 platform/architecture 问题。

... 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.

以下不提供目标类型的最大值。当目标类型范围超出unsigned的范围时失败,即~0U的类型。

// problem
unsigned_type_of_choice max_wannabe = ~0U;

您不应该将 ~0U 分配给任何无符号类型,chux's answer 已经解释了原因。

对于 C++,您可以获得所有无符号类型的最大可能值。

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

您正在否定您的确切类型的零。我使用了一个冗长的函数名称,因为它不应该用于有符号的值。问题是,要检查符号性,最简单的方法是包括一个额外的 header,即 type_traits. This other answer 然后会有用。

用法:

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> ();

返回值:(见测试代码here

255
65535
4294967295
18446744073709551615
4294967295

注意:对签名类型执行此操作要困难得多,请参阅 Programmatically determining max value of a signed integer type