4

I'm a bit confused:

long v = 0;
v <<= 8; 
v |= 230;

I know << is the signed left shift operator and | Bitwise the inclusive OR but I'm confused to what the equals does?

So fist v is 0. So << doesn't have any effect? Then it equals 1000 but what happens then?

edit: I've edited the title so others might better find this question: added "compound operators"

Thomas
  • 1,678
  • 4
  • 24
  • 47

3 Answers3

5

They're compound operators, like += and -= are. They do the operation, and then assign the result back to v.

Basically:

v <<= 8;

is in effect

v = v << 8;

And similarly

v |= 230;

is in effect

v = v | 230;

You can see the parallel with += and -=:

v += 1;

is effectively

v = v + 1;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
5

There are somewhat like +=.

For example x+=3 means add 3 to x; store to x.

v <<= 8;

left-shifts v 8 bits, and stores to v, functionally equivalent to v=v << 8.

v |= 230;

does a bitwise OR with 230 and stores back to v, equivalent to v=v | 230.

Now, due to performance constraints and optimizations this operation may be done in place at a low level.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

Basically, this:

v <<= 8; 
v |= 230;

is equivalent to this:

v = v << 8; 
v = v | 230;
jh314
  • 27,144
  • 16
  • 62
  • 82