Bit operations and some tips

Source: Internet
Author: User

Bit operations include the following :~ & ^ |, Indicating that bitwise is different from bitwise OR bitwise. The priority is reduced from left to right.

Bitwise AND operation have two typical usage: one is to take a few digits of a single bit string information. For example, the following code intercepts the minimum 7 digits of X: X & 0177. Second, let a variable retain a certain number of digits, and the remaining position is 0. For example, the following code keeps X at least 6 digits: x = x & 077.

A typical usage of bitwise OR operations is to set the location of a single bit string to 1. If you want to obtain the rightmost 4 bits as 1, the other bits must be the same as the other bits of the variable J. You can use the logic or operation 017 | J;

A typical usage of bitwise exclusive or operation is to reverse the information of a single bit string. For example, if you want to reverse the information of the rightmost 4 bits of the integer variable J, you can use the logic XOR operation 017 ^ J to reverse the information of the rightmost 4 bits of J, that is, the first bits, the result is 0, and the original value is 0. The result is 1. Exclusive or operations are particularly useful in solving some problems. Exclusive or specific properties: 0 ^ x = x, 1 ^ x = ~ X.

The most common examples of exclusive or is the use of x ^ x = 0. If two values are exchanged and temporary variables are not allowed, how can this problem be solved.

Solution: assume a = 3, B = 5. You can use the following three equations to complete the exchange: A = a ^ B, B = a ^ B, A = a ^ B. After the three statements are completed, the values of A and B are exchanged.

Bit operations and some tips

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.