位左移
假设我想将 i
向左移位两次并将值存储在 f
中。
f = i << 2;
这是正确的吗?我到底如何在 C/C++ 中做到这一点?
Let's say I want to bit shift i
twice to the left and store the value in f
.
f = i << 2;
Is that correct? How exactly do I do this in C/C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。
移位在许多位旋转操作中很有用。
这曾经是一个将数字乘以四的好方法。然而,如今,优化编译器往往会为您解决这个问题。
请记住,最左边的两位将被丢弃。
Yes.
Shifts are useful in a number of bit twiddling operations.
This used to be a great way to multiply a number by four. However, these days, optimizing compilers tend to take care of that for you.
Keep in mind that the two leftmost bits are discarded.
作为补充说明:即使您的问题被标记为
C++
,但可能值得注意的是,C 和 C++ 在移动负值方面采取了略有不同的路径。在 C++ 中,对负值执行<<
或>>
的结果是实现定义的。在 C 中,>>
是实现定义的,而<<
会产生未定义的行为。As an additional note: Even though your question is tagged
C++
, it is probably worth noting that C and C++ took slightly different paths with regard to shifting negative values. In C++ the result of doing<<
or>>
on a negative value is implementation-defined. In C>>
is implementation-defined, while<<
produces undefined behavior.是的,
i << 2,
f = i << 2
或f <<= 2
都是人们可能想要进行的移位操作。更多转变的事情要记住:
你还有
>>
。在位级别,>>
对于有符号和无符号类型的工作方式有所不同。<<
和>>
的优先级低于+
和-
,这愚弄了一些人,因为人们可能认为它们更像*
和/
。Yes,
i << 2
,f = i << 2
, orf <<= 2
are all things one might want to do to shift bits.More shift things to keep in mind:
you have
>>
as well. At the bit level,>>
works differently for signed and unsigned types.the priority of
<<
and>>
is below that of+
and-
, which fools some people, as one might imagine them to be more like*
and/
.为了完整地帮助您进行位运算,您可以查看此页面:uow 教科书 -> bitops.html
For the sake of completeness to help you with your bit operations you can check out this page: uow TEXTBOOK -> bitops.html