Bit Operators: Difference between << and <<= or >> and >>= in c
Please explain to me in detail the difference between << and <<= and as well as >> and >>=. I know how shift opera开发者_开发百科tors work, but I am not so sure about them when it comes to >>= or <<=.
Well <<
only shifts left. <<=
shifts left and assigns.
<<=
is to <<
what +=
is to +
.
EDIT
As suggested by MByD, here is an example
int x = 1;
/* Print 32. */
printf("%d\n", x << 5);
/* x stays the same. */
printf("%d\n", x);
x <<= 5;
/* x has become 32. */
printf("%d\n", x);
In C, and many other languages, you can put =
after an operator as a shortcut. Instead of writing...
x = x + 5
...I can write...
x += 5
These are called compound assignment operators. You're just seeing the versions of these for bit shift operations.
x >>= 1
...is the same as...
x = x >> 1
<< can be used on both variables and constants.
5 << 2; // this is ok.
a << 2; // this is ok too.
<<= will change the lvalue, so that:
a <<= 2; // bit-shifts a by two positions.
5 <<= 2; // wrong, 5 is 5 and will always be 5.
精彩评论