位左移

发布于 2024-08-08 17:37:51 字数 138 浏览 4 评论 0原文

假设我想将 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 技术交流群。

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

发布评论

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

评论(4

小清晰的声音 2024-08-15 17:37:51

是的。

f = i << 2

移位在许多位旋转操作中很有用。

这曾经是一个将数字乘以四的好方法。然而,如今,优化编译器往往会为您解决这个问题。

请记住,最左边的两位将被丢弃。

Yes.

f = i << 2

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.

我还不会笑 2024-08-15 17:37:51

作为补充说明:即使您的问题被标记为 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.

ˉ厌 2024-08-15 17:37:51

是的,i << 2,f = i << 2f <<= 2 都是人们可能想要进行的移位操作。

更多转变的事情要记住:

  • 你还有>>。在位级别,>> 对于有符号和无符号类型的工作方式有所不同。

  • <<>> 的优先级低于 +- ,这愚弄了一些人,因为人们可能认为它们更像 */

Yes, i << 2, f = i << 2, or f <<= 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 /.

黑白记忆 2024-08-15 17:37:51

为了完整地帮助您进行位运算,您可以查看此页面: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

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