c - 如何解释位右移两个不同的结果?

标签 c bitwise-operators

我得到了两个不同的结果,我很困惑,代码是:

int main () 
{
    int i = 0xcffffff3;
    printf("%x\n", 0xcffffff3>>2);
    printf("%x\n", i>>2);

    return 0;
}

结果是:

33fffffc
f3fffffc

最佳答案

这一切都归结为 0xcffffff3。那是一个十六进制整数常量。常量的类型取决于它的大小。引用C11 § 6.4.4.1 ¶ 5 :

The type of an integer constant is the first of the corresponding list in which its value can be represented.

Octal or Hexadecimal Constant - int, unsigned int, long int, unsigned long int, long long int, unsigned long long int

因此假设您的系统使用 32 位整数表示。 0xcffffff3 的类型是 unsigned int。

现在,当您执行 int i = 0xcffffff3; 时,无符号常量将转换为有符号整数。此转换产生负值。

最后,当右移时,它具有由 C11 §6.5.7 ¶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.

移动无符号常量产生 0xcffffff3/4,移动 i 产生一个实现定义的值(在本例中为负整数)。

关于c - 如何解释位右移两个不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43389598/

相关文章:

c++ - 返回 0 数组的数组按位或异或

r - 在R中找到整数中最低有效位的最快/最有效方法是什么?

通过指针改变值

c++ - 使用位实现集合

c - 为什么我会收到由于代码错误而无法显示图像的信息?

C 表达式必须有整型或枚举类型?

c - C 编程中的指针和字符串

c - 我试图使这段代码递归,但由于某种原因它不起作用

c - 以下 SLL 声明有何不同

bit-manipulation - 简化按位运算