Bit shifting left
Let's say I want to bit shift i
twice to the left and store the val开发者_StackOverflowue 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/
.
For the sake of completeness to help you with your bit operations you can check out this page: uow TEXTBOOK -> bitops.html
精彩评论