tags:

views:

257

answers:

4

How exactly do I do this in C/C++? Let's say I want to shift int i twice to the left and store the value in f.

f = i << 2 ?

I don't need this for a program or anything, I'm just interested in how it works. Thanks.

+6  A: 

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.

John Gietzen
For Intel CPUs, the last bit shifted out of the operand is stored in the carry flag. This doesn't really add to the relevant discussion, I just wanted to say it.
dreamlax
A: 

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

Robert Massaioli
+2  A: 

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

DigitalRoss
+3  A: 

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.

AndreyT