【问题标题】:Obtaining max of unsigned integer with bitwise not on zero value获得按位不为零的无符号整数的最大值
【发布时间】:2016-10-06 15:55:15
【问题描述】:

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

#include <iostream>
#include <limits>

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

我对这些之间的细微差别不是很有经验。这就是为什么我要询问使用第一种方法是否会出现一些意外行为或一些平台/架构问题。

【问题讨论】:

  • ~0U 很好。
  • 标准不保证二进制补码整数表示,所以这个技巧严格来说是不可移植的。实际上,它可能总是有效,但您应该更愿意将0 转换为预期类型,而不是指定为0U,即unsigned int。例如,当int 使用的位数少于long long 时,unsigned long long b = ~0U; 会为您提供不正确的最大unsigned long long 值。
  • 建议std::cout &lt;&lt; ((unsigned type of your choosing) -1) &lt;&lt; '\n';static_cast
  • 对这个问题的回答引用了似乎支持 chux 铸造 -1: stackoverflow.com/questions/21769068/… 的想法的新标准
  • @ChristopherOicles 这个问题没有负数,所以是否使用负数的 2 的补码表示并不重要

标签: c++ c bit-manipulation numeric-limits


【解决方案1】:

...获取某个无符号整数类型的最大值,不包含任何头文件

只需赋值-1

unsigned_type_of_choice max = -1;

-1(即int)转换为任何无符号类型都会导致比最大值大一的数字的值减1。

以下不提供目标类型的最大值。当目标类型范围超出unsigned 的范围时,它会失败,这是~0U 的类型。 @Christopher Oicles

// problem
unsigned_type_of_choice max_wannabe = ~0U;

【讨论】:

  • 引用了此(定义的)行为的文档hereHere 更清晰。
  • 该文档是 C++。我的目标是 C/C++ 解决方案。
  • 当然!要超级勤奋,要在两个标准中找到相应的部分,但这真的太费力了。无论如何,对于 C 可以参考here。我并没有深入,但是,虽然导致相同的结果,但针对 C 和 C++ 描述的机制不同。
【解决方案2】:

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

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

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

否定了您的确切类型的零。我使用详细的函数名称,因为它不应该用于有符号值。问题是检查签名最简单的方法是包含一个额外的标题,即type_traitsThis 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

【讨论】:

  • 不错的 C++ 解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多