c - 为什么 -(-2147483648) = - 2147483648 在 32 位机器上?

标签 c 32-bit twos-complement

我认为这个问题是不言自明的,我猜它可能与溢出有关,但我仍然不太明白。引擎盖下按位发生了什么?

为什么 -(-2147483648) = -2147483648(至少在用 C 编译时)?

最佳答案

否定一个(无后缀的)整数常量:

表达式 -(-2147483648) 在 C 中是完美定义的,但是为什么这样定义可能并不明显。

当您编写 -2147483648 时,它形成为应用于整数常量的一元减号运算符。如果2147483648不能表示为int,则表示为longlong long*(以先满足者为准),C 标准保证后一种类型涵盖该值

要确认这一点,您可以通过以下方式检查它:

printf("%zu\n", sizeof(-2147483648));

在我的机器上生成 8

下一步是应用第二个 - 运算符,在这种情况下,最终值为 2147483648L(假设它最终表示为 long).如果您尝试将其分配给 int 对象,如下所示:

int n = -(-2147483648);

然后实际行为是实现定义的。引用标准:

C11 §6.3.1.3/3 Signed and unsigned integers

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

最常见的方法是简单地截掉高位。例如,海湾合作委员会 documents它是:

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

从概念上讲,转换为宽度为 32 的类型可以通过按位与运算来说明:

value & (2^32 - 1) // preserve 32 least significant bits

根据two's complement算术上,n 的值由全零和 MSB(符号)位设置组成,表示 -2^31 的值,即 -2147483648.

取反 int 对象:

如果您尝试对 int 对象取反,该对象的值为 -2147483648,则假设是二进制补码机,程序将表现出未定义的行为:

n = -n; // UB if n == INT_MIN and INT_MAX == 2147483647

C11 §6.5/5 Expressions

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

其他引用资料:


*) 在被撤销的 C90 标准中,没有 long long 类型并且规则不同。具体来说,无后缀十进制的序列是 intlong intunsigned long int(C90 §6.1.3.2 整数常量)。

†) 这是由于 LLONG_MAX,它必须至少为 +9223372036854775807 (C11 §5.2.4.2.1/1)。

关于c - 为什么 -(-2147483648) = - 2147483648 在 32 位机器上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462352/

相关文章:

gcc - 如何在 64 位 RHEL 上编译 32 位应用程序?

c++ - 左移的负数是否*总是*用 "1"而不是 "0"填充?

C:处理24位2的补数的正确方法

c++ - GCC -flto 更改符号可见性

c - 在 C 中使用嵌套 for 循环打印星号模式

c - 我的代码运行不正常,没有打印它应该打印的所有行

将序列化结构从 8 位系统复制到 32 位系统

python - python Python : Cannot execute native linux-32 binary

c - 将数据添加到函数内部的结构中,但外部的值为空

javascript - 将二进制补码数转换为其二进制表示