C - 右移时看似无符号的 int 被符号扩展?

标签 c bit-shift unsigned-integer sign-extension

因此,我试图测试一个超短函数,以便从整数中获取 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/

相关文章:

C++:仅使用无符号类型时有符号/无符号不匹配

计算C中三角形的边长

c - 返回内容后如何释放指针

C++ 相当于 C 中的 Union 吗?

c - malloc返回0?

javascript - 如何在 PHP 中实现 JS 风格的按位左移运算符?

c - 正确的移位给出了错误的结果,有人可以解释一下吗

cpu - 如何在硬件层面上实现转变?

c++ - 现代编译器是否优化了 unsigned int 在 for 循环中的使用?

c - 使用 sscanf_s 时变量周围的堆栈已损坏