Bitwise operations are performed directly on the binary.
<< left shift 3<<2–> 3*2*2 like left two bit. Actually *2*2
3:0000 0011
Shift left two bit 0000 1100
>> Right Shift 3>>2–> 3/2/2/2/2
3:0000 0011
Move right two bit 0000 0000
When signed right shift, the highest bit is 0 with 0 complement, the highest bit is 1 with 1 complement.
-3 >> 2
-3 1000 0000 0000 0000 0000 0000 0000 0011 Original Code 1111 1111 1111 1111 1111 1111 1111 1100 anti-code 1111 1111 1111 1111 1111 1 111 1111 1101 Complement
Move right two-bit 11 1111 1111 1111 1111 1111 1111 1111 11 (01 missing) complement 1111 1111 1111 1111 1111 1111 1111 1111 1110 anti-code 1000 0000 0000 0 000 0000 0000 0000 0001 result IS-1
>>> right-shift operation without symbols
-3 >>> 2
-3 1000 0000 0000 0000 0000 0000 0000 0011 Original Code 1111 1111 1111 1111 1111 1111 1111 1100 anti-code 1111 1111 1111 1111 1111 1111 1111 1101 Complement
Shift right Two bit 00 1111 1111 1111 1111 1111 1111 1111 11 (01 missing) result is 1073741823
Note In Java, integers are stored by default in int, so it is 4 bytes.
& and operation of binary binary codes
| or operation, binary code, or operation
^ XOR operation of XOR binary code
~ Anti-code
12&5
12 of the original code (high 0 does not write)
12 0000 1100
5 0000 0101
& 0000 0100
Results 4
12|5
12 0000 1100
5 0000 0101
| 0000 1101
Results 13
12^5
12 0000 1100
5 0000 0101
^ 0000 1001
Results 9
~
12 0000 0000 0000 0000 0000 0000 0000 1100
~ 1111 1111 1111 1111 1111 1111 1111 0011 (sign bit change negative complement)
1111 1111 1111 1111 1111 1111 1111 0010 (anti-code)
1000 0000 0000 0000 0000 0000 0000 1101 (Original code)
Results: 13
int m = 5;
int n = 3
m = m^n;
n = m^n;
m = m^n;
m = m^n
n = m ^ n = (m ^ n) ^n = M =5
m = m ^n = (m ^ n) ^n = n = 3
5 0000 0101
3 0000 0011
^ 0000 0110 6
3 0000 0011
^ 0000 0101 5
Java Personal Learning Note: Bitwise operators