short int Integer wrap around / short int inversion in c 不理解,分配和打印之间的区别

short int Integer wrap around / short int inversion in c not understood, difference between assignment and prints

以下代码片段

short int k = -32768;
printf("%d \n", -k);
k=-k;
printf("%d \n", k);

打印

32768 
-32768

我会假设两个印刷品是一样的。 有人可以解释一下区别是什么以及为什么赋值 k=-k 会导致环绕吗?很难在网上找到解释,因为我真的不知道 google.

嗯,要打印一个short,需要用到长度修饰符。

将格式字符串更改为 %hd

因为 SHRT_MIN = -32768SHRT_MAX = +32767。查看 2 的补码如何工作。

编辑

实际上,根据 C 编程语言的国际标准(即 Committee Draft — May 6, 2005,第 50-51 页)关于有符号整数:

For signed integer types, the bits of the object representation shall be divided into three groups: value bits, padding bits, and the sign bit.

There need not be any padding bits; there shall be exactly one sign bit.

Each bit that is a value bit shall have the same value as the same bit in the object representation of the corresponding unsigned type (if there are M value bits in the signed type and N in the unsigned type, then M <= N).

If the sign bit is zero, it shall not affect the resulting value.

If the sign bit is one, the value shall be modified in one of the following ways:

  • the corresponding value with sign bit 0 is negated (sign and magnitude);

  • the sign bit has the value −(2N ) (two's complement);

  • the sign bit has the value −(2N − 1) (ones' complement).

Which of these applies is implementation-defined, as is whether the value with sign bit 1 and all value bits zero (for the first two), or with sign bit and all value bits 1 (for ones' complement), is a trap representation or a normal value. In the case of sign and magnitude and ones' complement, if this representation is a normal value it is called a negative zero.

因此,换句话说,在您的情况下似乎使用了 2 的补码,但这不应假定在所有平台和编译器中都适用。

-32768 是十六进制的 800032768 不能表示为带符号的 16 位数字,因此编译器将 -k 提升为具有十六进制值 00008000int。当这个数被赋值给 16 位变量时,高位被截断,导致再次 8000-32768