Java bitwise operators "and &", "not ~", "or |", "exclusive or ^"

Bit operators are mainly for binary, which includes: "and", "not", "or", "exclusive or". On the surface, it seems a bit like logical operators, but logical operators perform logical operations on two relational operators, while bitwise operators mainly perform logical operations on the bits of two binary numbers. Each bitwise operator is described in detail below.

 


1. The AND operator
The AND operator is represented by the symbol "&", and its usage rule is as follows:
the result is 1 when both operands are 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("The result of the AND of a and b is: "+(a&b));
}
}
run The result
of the sum of a and b is: 128
Let's analyze this program:
The value of "a" is 129, which is 10000001 when converted to binary, and the value of "b" is 128, which is 10000000 when converted to binary. According to the operation rule of the AND operator, only if both bits are 1, the result is 1, and it can be known that the result is 10000000, which is 128.

 


2. The OR operator
or operator is represented by the symbol "|", and its operation rule is as follows:
as long as one of the two bits is 1, then the result is 1, otherwise it is 0. Let's look at a simple example.
public class data14
{
public static void main(String[] args)
{
int a=129;
int b=128;
System.out.println("The result of OR of a and b is: "+(a|b));
}
} The result of
running result
a and b OR is: 129
The following analysis of this program segment:
The value of a is 129, which is 10000001 when converted into binary, and the value of b is 128, which is 10000000 when converted into binary. According to the operation rule of the OR operator , only one of the two bits is 1, and the result is 1. You can know that the result is 10000001, which is 129.

 


3. NOT operator
The NOT operator is represented by the symbol "~", and its operation rules are as follows:

If the bit is 0, the result is 1, if the bit is 1, the result is 0. Let's see a simple example.
public class data15
{
public static void main(String[] args)
{
int a=2;
System.out.println("The result of non-a is: "+(~a));
}
}

 


4.异或运算符
异或运算符是用符号“^”表示的,其运算规律是:
两个操作数的位中,相同则结果为0,不同则结果为1。下面看一个简单的例子。
public class data16
{
public static void main(String[] args)
{
int a=15;
int b=2;
System.out.println("a 与 b 异或的结果是:"+(a^b));
}
}
运行结果
a 与 b 异或的结果是:13
分析上面的程序段:a 的值是15,转换成二进制为1111,而b 的值是2,转换成二进制为0010,根据异或的运算规律,可以得出其结果为1101 即13。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326169654&siteId=291194637