c - C中按位运算符的不同结果

标签 c bitwise-operators bit-shift

为了在c中实现逻辑右移,在网上搜索得到如下C代码

int a, b, c;
int x = -100;
a = (unsigned) x >> 2;
b = (0xffffffff & x) >> 2;
c = (0x0 | x ) >> 2;

现在a和b都是逻辑右移结果(1006632960),但是c仍然是算术右移结果(-25),谁能解释一下为什么?谢谢

最佳答案

b = (0xffffffff & x) >> 2;

假设您的整数是 32 位,文字常量 0xffffffff 的类型是 unsigned int,因为它太大而无法放入普通 int & 介于 unsigned intint 之间,在这种情况下,根据定义无符号类型优先。因此,转移发生在无符号上;因此它从左边移入 0 位。

c = (0x0 | x ) >> 2;

0x0 的类型默认为 int 因为它足够小以适合,所以按位或发生在 int 上,下面的移位也是如此。它是实现定义的,当您将有符号整数右移时会发生什么,但大多数编译器会产生符号扩展的算术移位。

关于c - C中按位运算符的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997176/

相关文章:

c# - 如何将字节数组转换为uint64并返回C#?

protocol-buffers - Google Protocol Buffer :ZigZag编码

c++ - C++中的算术与逻辑移位运算

c - 关系运算符 == 在 C 中如何工作?

c++ - 使用 cmake 在 Linux for Windows 上交叉编译程序

c - 为什么在使用 scanf() 和 printf() 时没有执行 else 语句?

c++ - 按位与 : why do I get this behaviour?

c - 位操作快速 strlen

C题: off_t (and other signed integer types) minimum and maximum values

c - 如何将 UTF-8 字符串转换为大写?