为什么按位右移似乎不起作用?
有人可以向我解释为什么面具根本没有移到右边吗? 您可以使用任何值来代替 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个类型问题。 如果将 0 转换为无符号,那就没问题了:
按评论编辑:或使用无符号文字表示法,这样更简洁。 :)
It's a type issue. If you cast the 0 to unsigned it'll be fine:
Edit per comments: or use unsigned literal notation, which is much more succinct. :)
签名扩展
发生的事情是
~0
是一个包含所有位的 int设置(-1
)。 现在你右移1
; 由于它是-1
,符号扩展保留最高位设置,因此它保持签名状态(这不是您所期望的)。 然后它会像您期望的那样转换为无符号。Sign extension
What's happening is
~0
is an int with all bits set (-1
). Now you right shift by1
; 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.试试这个:
分配的 RHS 被视为有符号量,除非您强制转换它,这意味着您看到的是没有强制转换的符号扩展。 (我还更改了您的打印语句以显示十六进制数字,这对我来说更容易解码。)
Try this:
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.)
~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.