Home > Java > javaTutorial > body text

How to operate XOR in Java?

藏色散人
Release: 2020-09-17 14:51:36
Original
23019 people have browsed it

The XOR operation in Java is based on binary data; that is to say, when the XOR operation is used in the code, the two conditions will be converted first, and then converted into binary data. Operation. Operation rules: In the same bit of the two operands, if the values ​​​​are the same (both 0 or both 1), it is 0, and if they are different (one is 0, the other is 1), it is 1.

How to operate XOR in Java?

The bitwise operators in Java are mainly for binary, which include: "AND", "NOT", "OR", "XOR". On the surface, it seems a bit like logical operators, but logical operators perform logical operations on two relational operators, while bit operators mainly perform logical operations on the bits of two binary numbers.

The following is an introduction to the use of the XOR operator:

XOR operator

The XOR operation (^) is based on binary data. Basic calculations. That is to say, when the XOR operation is used in the code, the two conditions will be converted first and converted into binary data before the operation is performed. If the same bits in different fields have the same value (both are 0 or both are 1), they are 0, and if they are different (one is 0, the other is 1), they are 1.

The operation rule is: if the bits of the two operands are the same, the result is 0, and if they are different, the result is 1.

Let’s look at a simple example.

public class data16
{
public static void main(String[] args)
{
int a=15;
int b=2;
System.out.println("a 与 b 异或的结果是:"+(a^b));
}
}
Copy after login

Running result

The result of XOR between a and b is:

13
Copy after login

Analyze the above program segment: the value of a is 15, conversion It is 1111 in binary system, and the value of b is 2, and it is 0010 in binary system. According to the operation rules of XOR, it can be concluded that the result is 1101 or 13.

The above is the detailed content of How to operate XOR in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template