简体   繁体   中英

java bitwise operators and the equal character; compound operators

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"

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;

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 v=v | 230 .

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

Basically, this:

v <<= 8; 
v |= 230;

is equivalent to this:

v = v << 8; 
v = v | 230;

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