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

考虑以下代码来设置x的所有位
unsigned int x = -1;

这是便携式吗?至少Visual Studio 2005-2010似乎有效

解决方法

引用沉重的答案:

我知道这里有很多正确的答案,但是我想添加一些引用.我将引用两个标准:C99 n1256草案(免费提供)和C n1905草案(也可免费提供).没有什么特别的这些特定的标准,他们只是免费提供,什么发生了最容易找到的时刻.

C版本:

§5.3.2¶9:根据本段,值(〜)类型保证所有位都被设置,如果(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必须是类型中最大的数字(由于所有位都打开,每一位都是加法).

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,因此(类型)-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必须设置所有位.

摘要

是的,它是便携式的.无符号类型x = -1;保证根据标准设置所有位.

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...