如何在 c 中执行带符号的右移 (>>)?

How do I perform a signed right shift(>>) in c?

如何在 c 语言中执行有符号右移? 比如 -25 >> 3.

我这样试过: 10011001 >> 3 == 00010011

但是结果是-4。

一个带符号的右移。在有符号移位中,负数(由最高位中的“1”标识)通常从左侧填充。 (虽然这取决于特定的编译器。看起来这就是你的编译器正在做的事情。) 11100111 --> 11110011 --> 11111001 --> 11111100

听起来您要找的是一个无符号班次。如果您使用 (signed char)(((unsigned char)-25)>>3),您可能会得到您想要的结果。

按照标准6.5.7p5

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.

结果是实现定义的,您应该查看它是如何定义的。

假设二进制补码和符号右移,-2511100111,将它移动3将导致11111100,即-4

由于有符号整数的右移是根据我的经验定义的实现,因此结果取决于目标机器上算术移位的可用性。因为现在很难找到没有它的任何计算机或uC几乎总是算术右移的结果

来自维基百科: