Bit shifting left

心已入冬 提交于 2019-12-23 01:35:12

问题


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++?


回答1:


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.




回答2:


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.




回答3:


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 /.




回答4:


For the sake of completeness to help you with your bit operations you can check out this page: uow TEXTBOOK -> bitops.html



来源:https://stackoverflow.com/questions/1604368/bit-shifting-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!