为什么按位右移似乎不起作用?

发布于 2024-07-14 07:13:39 字数 132 浏览 12 评论 0原文

有人可以向我解释为什么面具根本没有移到右边吗? 您可以使用任何值来代替 1,结果是相同的。

unsigned mask = ~0 >> 1;
printf("%u\n", mask);

Could someone explain to me why the mask is not shifted to the right at all? You can use anything in place of that 1 and the result will be the same.

unsigned mask = ~0 >> 1;
printf("%u\n", mask);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烟燃烟灭 2024-07-21 07:13:39

这是一个类型问题。 如果将 0 转换为无符号,那就没问题了:

unsigned mask = ~ (unsigned) 0 >> 1;
printf("%u\n", mask);

按评论编辑:或使用无符号文字表示法,这样更简洁。 :)

unsigned mask = ~0u >> 1;
printf("%u\n", mask);

It's a type issue. If you cast the 0 to unsigned it'll be fine:

unsigned mask = ~ (unsigned) 0 >> 1;
printf("%u\n", mask);

Edit per comments: or use unsigned literal notation, which is much more succinct. :)

unsigned mask = ~0u >> 1;
printf("%u\n", mask);
似最初 2024-07-21 07:13:39

签名扩展

发生的事情是 ~0 是一个包含所有位的 int设置(-1)。 现在你右移1; 由于它是 -1,符号扩展保留最高位设置,因此它保持签名状态(这不是您所期望的)。 然后它会像您期望的那样转换为无符号。

Sign extension

What's happening is ~0 is an int with all bits set (-1). Now you right shift by 1; since it's -1, sign extension keeps the highest bit set so it remained signed (this is not what you were expecting). Then it's converted to unsigned like you expect.

ζ澈沫 2024-07-21 07:13:39

试试这个:

unsigned mask = (unsigned) ~0 >> 1;
printf("%08x\n", mask);

分配的 RHS 被视为有符号量,除非您强制转换它,这意味着您看到的是没有强制转换的符号扩展。 (我还更改了您的打印语句以显示十六进制数字,这对我来说更容易解码。)

Try this:

unsigned mask = (unsigned) ~0 >> 1;
printf("%08x\n", mask);

The RHS of the assignment is treated as a signed quantity unless you cast it, which means you were seeing sign extension without the cast. (I also changed your print statement to display the number in hex, which is easier for me to decode.)

拒绝两难 2024-07-21 07:13:39

~0 是一串 1。 >> 运算符对它们进行移位,在有符号值中,它将它们移位到高位。 所以你可以随意改变,结果不会改变。

~0 is a string of ones. The >> operator shifts them, and in a signed value, it shifts ones into the higher order bits. So you can shift all you want, the result won't change.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文