简体   繁体   中英

Bit shifting left

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

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.

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 .

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

为了完整起见,可以帮助您进行位操作,您可以查看以下页面: uow TEXTBOOK-> bitops.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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