c - c 中负值的位移位

标签 c bit-manipulation

<分区>

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/

相关文章:

c - 如何将文件中的字符串和 float 存储到结构中?

c - struct数组的数据结构

C套接字内存溢出

python - 在 OS X 中运行进程,查找启动进程

c - 系统调用 open() 权限

c - 在 C 中使用未声明的标识符 'a'

c - 我如何在C中将指针的最右边位设置为1

java - Java中基于位板的数组生成问题

java - 按负数移动

c - 具有 htonl 和 ntohl 功能的 pdp endian