解决方法
我知道这里有很多正确的答案,但是我想添加一些引用.我将引用两个标准: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.但是,如果您使用指针转换(通常不是便携式的),则只能发现这一点.