Common usage of C + + bit operations Summary _c language

Source: Internet
Author: User

In this paper, the common usage of C + + bit operation is summarized with the example form. Share for everyone to use for reference. The specific methods are as follows:

There are 6 basic operators in the C + + bitwise operation, which are, by priority:

Take the Counter ~
Shift << >>
and &
Different or ^
or |

Common uses are:

1 to judge even, the lowest bit is 0 or 1 can be, faster than the model

X 2!= 0    //x positive and negative can be judged; do not x%2 = = 1, because if X is negative odd, X%2=-1
x & 0x1 = 0 

2 Exchange two numbers without intermediate variables

void Myswap (int &a, int &b)
{
  if (a = = b)  //equal can also get the correct result, but no need to return
    ;

  a ^= b;
  b ^= A;
  a ^= b;
}

3 to find the number of 1 in the binary representation of an integer, without a single shift to judge

int numOfBit1 (int a)
{
  int cnt = 0;
  while (a!= 0)
  {
  ++cnt;
  A &= A-1;  The rightmost 1 is set to 0, both positive and negative are calculated, negative numbers are calculated according to the complement, and the last sign bit is also counted
  } return
  cnt;
}

4 positive and negative conversion, do not use the sign. No matter positive or negative, add 1 to the back

int a = 1;
A = ~a + 1;  A becomes-1
a = ~a + 1;  A turns 1 again.

5 absolute value, do not judge positive numbers, do not use positive and negative, return absolute value

int myabs (int a)
{
  int sign = a >>;    If a is positive, sign is 0, otherwise sign is-1, or 0xFFFFFFFF return
  (a^sign)-sign;  (a^0)-0 = A, (a^-1)-( -1) = ~a+1 =-A, a^-1 is a take-back
}

I hope this article will help you with the learning of C + + programming.

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.