I trying to know to know how java finds the result is -ve or +ve for Bitwise operations?
int x=-5;
int y=8;
System.out.println(x&y); //8
System.out.println(x|y); //-5
x->1 0 1 1 (2's complement)
y->1 0 0 0
x & y -> 1 0 0 0 ->8
x | y -> 1 0 1 1 ->-5(2's complement)
How java knows 1 0 1 1 is -5 ?
why doesn't it directly give o/p as 1 0 1 1's decimal equivalent 11 ?
Does it apply 2's complement on every result ?
I have seen the Assembly Code . It is IAND and IOR instructions.
You are running the bitwise operators on 32-bit integers. So, the number "8" really has a lot of zeros in front, while "-5" has a lot of ones:
8 -> 0...01000
-5 -> 1...11011
So, Java does not need to "know" anything about the outcome or operands of the bitwiese operations. The "8" is a 32-bit number that starts with a 0, so it is positive. The "-5" is a 32-bit number that starts with a "1", so it is negative.
So, the answer to your question
Does it apply 2's complement on every result ?
is: Yes, since all integers are signed number in Java, using 2's complement.