The bitwise operator is primarily for binary, which contains: "and", "Non", "or", "XOR". On the surface it seems a bit like a logical operator, but the logical operator is a logical operation on two relational operators, while the bitwise operator is mainly for the bits of two binary numbers. Each digit operator is described below.
1. With operator
With the operator denoted by the symbol "&", its usage rules such as the following:
Each of the two operand bits is 1, the result is 1, otherwise the result is 0, such as the following program segment.
public class Data13
{
public static void Main (string[] args)
{
int a=129;
int b=128;
System.out.println ("A and B" with the result is: "+ (a&b));
}
}
Execution results
A and B with the result is: 128
The following analysis of this program:
The value of "a" is 129, converted to binary is 10000001, and the value of "B" is 128, converted to binary is 10000000. According to the Operation Law of operators, only two bits are 1, the result is 1, can know the result is 10000000, that is 128.
2. Or operator
Or operator with the symbol "|" Indicates that its operation law is as follows:
Two bits only have one for 1, then the result is 1, otherwise 0, see a simple example below.
public class Data14
{
public static void Main (string[] args)
{
int a=129;
int b=128;
System.out.println ("A and B" or the result is: "+ (a|b));
}
}
Execution results
A and B or the result is: 129
The following analysis of this program segment:
The value of a is 129, converted to binary is 10000001, and the value of B is 128, converted to binary is 10000000, according to or operator of the Operation Law, only two bits have a 1, the result is 1, can know the result is 10000001, that is 129.
3. Non-operator
The non-operator is denoted by the symbol "~", and its Operation law is as follows:
Assuming a bit of 0, the result is 1, assuming that the bit is 1, the result is 0, the following is a simple example.
public class Data15
{
public static void Main (string[] args)
{
int a=2;
SYSTEM.OUT.PRINTLN ("A non-result is:" + (~a));
}
}
4. Xor operator
The XOR operator is denoted by the symbol "^", and its Operation law is:
Two operand bits, the same result is 0, the result is 1. Here is a simple example.
public class Data16
{
public static void Main (string[] args)
{
int a=15;
int b=2;
System.out.println ("A and B xor the result is:" + (a^b));
}
}
Execution results
The result of A and B xor is: 13
Analysis of the above program segment: The value of a is 15, converted to binary 1111, and the value of B is 2, converted to binary 0010, according to the different or the Operation law, can be obtained the result of 1101 is 13.
Java bitwise operators specifically explain instances-with (&), non-(~), or (|), XOR (^)