Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2^0*2 and (2^0)*2?

I have expected both expression's will give same answer:

System.out.println(2^0*2);
System.out.println((2^0)*2);

Output:

2
4

Is there a specific reason why 2^0*2 = 2 and (2^0)*2 = 4?

like image 369
Prakash VL Avatar asked Jan 06 '23 07:01

Prakash VL


1 Answers

You have wrongly assumed that ^ operator behaves the same like the exponentiation in math.

At the first sight you can see that ^ is understood as + operator. Actually it means bitwise XOR operator.

System.out.println(2^0*2);   //  2 XOR 0  * 2 = 2
System.out.println((2^0)*2); // (2 XOR 0) * 2 = 4
System.out.println(2^4);     //  2 XOR 4      = 6

The XOR is exclusive disjunction that outputs true only when inputs differ. Here is the whole trick:

2^0 = 2 XOR 0 = (0010) XOR (0000) = (0010) = 2 
2^4 = 2 XOR 4 = (0010) XOR (0100) = (0110) = 6
like image 117
Nikolas Charalambidis Avatar answered Jan 15 '23 19:01

Nikolas Charalambidis