c - 表达式中移位和按位补码的反转优先级

标签 c bitwise-operators shift short

在此代码中:

unsigned short int i = 3;
unsigned short int x = 30;
unsigned short int z = (~x) >> i;

在第三行,即使我使用括号,它似乎也会先进行移位,然后进行补码 (~)。

但是,如果我将 short 替换为 long,就不会出现奇怪的结果。 它在 Windows 和 Unix 中都会发生。这是为什么?

最佳答案

它完全按照您指定的顺序执行操作。

但是,操作数不是无符号短整型。在执行操作之前,积分提升会将 xi 转换为良好的旧式常规有符号整数。引用 C 标准:

6.3.1 Arithmetic operands / paragraph 2

The following may be used in an expression wherever an int or unsigned int may be used:

  • An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int.

在您尝试过的机器上,无符号短裤可以完美地放入有符号整数中。

此外,右移有符号整数具有实现定义的负值结果:

6.5.7 Bitwise shift operators / paragraph 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.

~x 是某个负整数(具体取决于有符号整数的值表示)。

以上所有情况很可能会导致您在将其转换回无符号短整数时无法获得预期结果。

关于c - 表达式中移位和按位补码的反转优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752182/

相关文章:

c - 管道问题 : first child writes too much in to pipe

c - Linux : Check if message queue is empty

python - 使用 OpenCV 删除部分图像

c - gcc 中的优化级别改变了 c 程序的行为

jquery - 按住 Shift 键单击 bootstrap/FlatUI 复选框

c - 左移后面加 1? C语言

c - 在 C 中使用 ' vs "会发生什么?

检查矩阵中的行数是否等于 c 中的给定行数

c - 什么是位掩码?

c++ - 一种直接根据掩码转位的方法