c++ - 将 -1 转换为无符号类型

标签 c++

考虑以下代码来设置x

的所有位
unsigned int x = -1;

这是可移植的吗?它似乎至少适用于 Visual Studio 2005-2010

最佳答案

引用较多的答案:

我知道这里有很多正确答案,但我想添加一些引用。我将引用两个标准:C99 n1256 草案(免费提供)和 C++ n1905 草案(也免费提供)。这些特定标准没有什么特别之处,它们都是免费提供的,而且是目前最容易找到的任何东西。

C++版本:

§5.3.2 ¶9:根据本段,值 ~(type)0 保证设置所有位,如果 (type) 是一个无符号类型。

The operand of ~ shall have integral or enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand.

§3.9.1 ¶4:这解释了溢出如何处理无符号数。

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

§3.9.1 ¶7,加上脚注 49:这解释了数字必须是二进制的。由此,我们可以推断出 ~(type)0 一定是 type 中可表示的最大数字(因为它所有的位都打开了,而且每一位都是可加的)。

The representations of integral types shall define values by use of a pure binary numeration system49.

49) A positional representation for integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral power of 2, except perhaps for the bit with the highest position. (Adapted from the American National Dictionary for Information Processing Systems.)

由于算术是以 2n 为模进行的,因此可以保证 (type)-1 是该类型中可表示的最大值。它还保证 ~(type)0 是该类型中可表示的最大值。因此它们必须相等。

C99版本:

C99 版本以更紧凑、更明确的方式拼写出来。

§6.5.3 ¶3:

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

与在 C++ 中一样,无符号算术保证是模块化的(我想我现在已经对标准进行了足够的挖掘),因此 C99 标准绝对保证 ~(type)0 == (type)- 1,我们从 §6.5.3 ¶3 知道 ~(type)0 必须设置所有位。

总结:

是的,它是可移植的。 unsigned type x = -1; 保证根据标准设置所有位。

脚注:是的,我们谈论的是值位而不是填充位。但是,我怀疑您是否需要将填充位设置为 1。您可以从最近的 Stack Overflow 问题 (link) 中看到,GCC 已移植到 PDP-10,其中 long long 类型具有单个填充位。在这样的系统上,unsigned long long x = -1; 可能不会将该填充位设置为 1。但是,您只有在使用指针转换时才能发现这一点,这通常不是反正是便携的。

关于c++ - 将 -1 转换为无符号类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8208023/

相关文章:

c++ - 想要创建自己的类 String

c++ - KMP算法的时间复杂度

c++ - winsock2中发送其他数据类型

c++ - 将 vector<int32_t> 转换为 int[] 的最佳方法是什么

c++ - 检查 QBool 在 Qt 中是否可用

c++ - 无法访问 vector 大小

c++ - 类声明的循环依赖

c++ - 用排序仿函数实现多态性

具有构造函数的 c++ 对象将值放入封装对象中

c++ - 从 emacs 中的源代码中收集并显示 c++ TODO 注释列表