Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does " |= "and " ^= " mean in java? [duplicate]

Tags:

java

this is a function for changing bit value of image. what does |= and ^= mean?

private int setBitValue(int n,int location,int bit)  {
    int toggle=(int)Math.pow(2,location),bv=getBitValue(n,location);
    if(bv==bit)
       return n;
    if(bv==0 && bit==1)
       n|=toggle;        // what does it do?
    else if(bv==1 && bit==0)
       n^=toggle;        // what does it do?

    return n;
}
like image 336
Keertan Avatar asked Feb 06 '14 11:02

Keertan


People also ask

What does |= mean in Java?

The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.

What is the meaning of a |= 4 in Java?

|= is a bitwise-OR-assignment operator. It takes the current value of the LHS, bitwise-ors the RHS, and assigns the value back to the LHS (in a similar fashion to += does with addition).

Is |= the same as +=?

Save this answer. Show activity on this post. |= reads the same way as += .

What is >> and << in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.


3 Answers

Its the same short form as in +=

n |= toogle

is the same as

n = n | toogle

the | is here the binary-or operator and ^ is the binary xor-operator

like image 159
Mikescher Avatar answered Oct 19 '22 11:10

Mikescher


They are short hand assignment operations.

n|=toggle;       is equivalent to           n=n|toggle;

and

n^=toggle;       is equivalent to           n=n^toggle;

And

| is bitwise OR    
^ is bitwise XOR
like image 23
4J41 Avatar answered Oct 19 '22 13:10

4J41


They're the bitwise OR equals and the bitwise XOR equals operators. They are mainly used for dealing with bit flags. I highly recommend this article if you want to learn more about bitwise and bit-shifting operations.

like image 1
Someone Avatar answered Oct 19 '22 13:10

Someone