因此,我试图测试一个超短函数,以便从整数中获取 x 到 y 某些位的整数值,但在发生符号扩展时遇到了一些问题。我尝试转换为无符号整型,然后使用无符号整型进行移位,但这似乎不起作用。代码如下:
#include <stdio.h>
int main()
{
int bo_bits = 2;
int tag_bits = 28;
int addr = 1;
unsigned int index = (unsigned int)addr;
index = index << tag_bits;
index = index >> bo_bits;
// at this point I would return (int)index;
return 0;
}
我不明白为什么会发生符号扩展,因为我只对无符号整数进行了移位。我还仅使用“addr”运行代码并将其作为无符号整数,但这也没有改变输出。
当我在Linux机器上的gdb中运行该函数时,索引的输出值为536870912,在线编译(现在编码地面)时,我得到的值为67108864。
编辑:有几个人问我如何获得值 536870912,我已经通过两个断点运行 gdb 并从 gdb 运行命令 p get_index(1)
。实际代码如下:
unsigned int index = (unsigned int)addr;
index = index << tag_bits;
index = index >> bo_bits;
return (int)index;
感谢您的帮助!
最佳答案
536870912 等于 1 << 29,这意味着它与符号扩展无关。
也许是你在调试程序时停在错误的地方
这是 c99 标准关于按位右移的说法。 (6.5.7 Bitwise shift operators)
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 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
关于C - 右移时看似无符号的 int 被符号扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198840/