Bitwise operations that cannot be underestimated

Source: Internet
Author: User

1. Determine whether it is 2 ^ n

! (X & (x-1 ))

2. Calculate the average value of two numbers
(X & y) + (x ^ y)> 1)


3. count the number of 1 contained in a number (converted to binary)
While (x) {cout ++; x = x & (x-1 );}


4. Compare the two numbers
Int c = a-B; char * strs [2] = {"a", "B"}; c = unsigned (c)> (sizeof (int) * 8-1); // 1B = 8b // convert the result to an unsigned type. If the result is negative, then 32nd bits // that is, the number of signed symbols is 1, and the opposite is 0. therefore, you can shift the slash (/) to the right to obtain the symbol bit and use it as the subscript of the result array. Cout <

 

  

5. Exchange the values of a and B without any intermediate variables.


(1) General Practice
Int a = 0x7ffffffe; int B = 0x7fffffff; cout <"a =" <
In the programmer interview book, one drawback is that when a = a + B, if a and B are large, they will be super-qualified! However, I don't know what super world can do. You can still get the correct result. Therefore, I think this method is good and has no disadvantages.

(2) bitwise operations

Int a = 0x7ffffffe; int B = 0x7fffffff; cout <"a =" <

In general, it is a good choice to use bitwise operations, and it is easy to remember. The problem comes from the programmer interview book

Related Article

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.