Bitwise Operators
Java defines a number of bitwise operators that can be applied to integer types Long,int,short,char and byte.
Bitwise operators are performed on BITS and perform bitwise operations. Suppose a = 60 and B =; now in binary format, they will be as follows--
A = 0011 1100
b = 0000 1101
-----------------
A&B = 0000 1100
A | b = 0011 1101
a ^ b = 0011 0001
A = 1100 0011
Assuming that the integer variable a remains 60 and the variable B remains 13, then-
Public class test { public static void main (String args[]) { int a = 60;/* 60 = 0011 1100 */ int b = 13;/* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ system.out.println ("a & b = " + c ); c = a | b; /* 61 = 0011 1101 */ system.out.println ("a | b = " + c ); c = a ^ b; /* 49 = 0011 0001 */ system.out.println ("a ^ b = " + c ); c = ~a; /*-61 = 1100 0011 */ system.out.println ("~a = " + c ); c = a << 2; /* 240 = 1111 0000 */ system.out.println ("a << 2 = " + c ); c = a >> 2; /* 15 = 1111 */ system.out.println ("a >> 2 = " + c "; c = a >>> 2; / * 15 = 0000 1111 */ system.out.println ("a >>> 2 = " + c "; }}
Output results A & b = 12a | b = 61a ^ b = 49~a = -61a << 2 = 240a >> 15a >>> 15
Summarize:
& (Bitwise AND) |
If the binary and operator exists in two operands, the binary and operator will copy one bit to the result. |
(A and B) will give 12 is 0000 1100 |
| (bitwise OR) |
The binary or operator copies a bit if it exists in any of the operands. |
(A | B) will give 61, which is 0011 1101 |
^ (Bitwise XOR) |
The binary XOR operator copies the bit if it is set in an operand, not both. |
(A ^ B) will give 49, which is 0011 0001 |
(praised by the person) |
The binary complement operator is unary and has the effect of a "flip" bit. |
(A) will give 61, because of the signed binary number, it is 2 0 of the complement form of 1100 0011. |
<< (shift left) |
Binary left-shift operator. the left action value moves left by the number of digits specified by the right operand. |
A << 2 will give 240 is 1111 0000 |
>> (move right) |
The binary right-shift operator. the left action value is moved by the bit specified by the right operand. |
A >> 2 will give 15 is 1111 |
>>> (0 fill right shift) |
Move the 0 fill operator right. the left action value is shifted right by the number of digits specified by the right operand, and the shift value is padded with 0. |
A >>> 2 will give 15 is 0000 1111 |
This article is from the "Man On Dream Road" blog, please make sure to keep this source http://meyangyang.blog.51cto.com/12906086/1926831
Explanation of the JAVA bitwise operator