Simple analysis of Java bitwise operator calculation method

Source: Internet
Author: User
Tags bitwise

Tag: XOR represents print AMP analysis based on nbsp operation conversion

The bitwise operator is primarily for binary, and it includes: "and", "or", "XOR".

1. With operator (& representation)
The operation rules are as follows:
The two operands have a bit of 1 and the result is 1, otherwise the result is 0, for example:

int a=5;
int b=2;
System.out.println ("A and B" with the result is: "+ (a&b));

Operation Result:
A and B with the result is: 0
Analysis:
The value of a is 5, the conversion to binary is 101, and the value of B is 2, and the conversion to binary is 10. According to the operator's operation Law, only two bits are 1, the result is 1, you can know the result is 000, that is, 0.

2. Or operator (| representation)
The operation rules are as follows:
Two bits as long as there is a 1, then the result is 1, otherwise 0, for example:

int a=5;
int b=2;
System.out.println ("A and B" or the result is: "+ (a|b));

Operation Result:
A and B or the result is: 7
Analysis:
The value of a is 5, the conversion to binary is 101, and the value of B is 2, converted to binary is 10, according to the operator's operation Law, only two bits have a 1, the result is 1, you can know the result is 111, that is 7.

3. Xor operator (^ representation)
The rules of operation are:
The two operand bits, the same result is 0, and the result is 1. Let's look at a simple example.

int a=15;
int b=2;
System.out.println ("A and B xor the result is:" + (a^b));

Run results
The result of A and B xor is: 13
Analysis:

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 of the law, you can conclude that the result is 1101 or 13.

Features: A number XOR or itself becomes 0; a number xor or 0 is itself.

Simple analysis of Java bitwise operator calculation method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.