简体   繁体   English

左移

[英]Bit shifting left

Let's say I want to bit shift i twice to the left and store the value in f . 假设我想将i左移两次,然后将值存储在f

f = i << 2;

Is that correct? 那是对的吗? How exactly do I do this in C/C++? 如何在C / C ++中做到这一点?

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. 这曾经是将数字乘以4的好方法。 However, these days, optimizing compilers tend to take care of that for you. 但是,如今,优化编译器往往会为您解决这一问题。

Keep in mind that the two leftmost bits are discarded. 请记住,最左边的两个位被丢弃。

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. 需要特别注意的是:即使您的问题被标记为C++ ,也可能值得注意的是C和C ++在转移负值方面采取了略有不同的路径。 In C++ the result of doing << or >> on a negative value is implementation-defined. 在C ++中,对负值执行<<>>的结果是实现定义的。 In C >> is implementation-defined, while << produces undefined behavior . 在C中>>是实现定义的,而<<产生未定义的行为

Yes, i << 2 , f = i << 2 , or f <<= 2 are all things one might want to do to shift bits. 是的, i << 2f = i << 2f <<= 2都是人们想要做的所有移位位的事情。

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 TEXTBOOK-> bitops.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM