<分区>
int16_t a = -1;
a >>= 2;
a的值是多少, 答案是 -1 还是 0,你能解释一下为什么吗?
是发生整数除法然后使用 floor 函数,还是简单地将 2 补码中的所有 1 向右移动从而导致仍然为 -1,或者它是否截断除法导致 0。
<分区>
int16_t a = -1;
a >>= 2;
a的值是多少, 答案是 -1 还是 0,你能解释一下为什么吗?
是发生整数除法然后使用 floor 函数,还是简单地将 2 补码中的所有 1 向右移动从而导致仍然为 -1,或者它是否截断除法导致 0。
最佳答案
对于 C Language Draft 6.5.7 Bitwise shift operators 5 :
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined
这意味着它是正确的,不是未定义的行为,但每个编译器可能决定用 1 或 0 填充位。
结果可以是 -1(填充 1 位)或 16383 = 0x3FFF(填充 0 位)
关于c - c 中负值的位移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963784/