Summary of common usage of C++ bit operations
- 2020-04-02 02:43:13
- OfStack
This article summarizes the common usage of C++ bit operations in the form of examples. Share with you for your reference. Specific methods are as follows:
In C++, there are six basic operators for bitwise operations.
The not
~
shift
<
<
>
>
with
&
Exclusive or
^
or
|
Common usage:
1 to determine the even number, the lowest order is 0 or 1, faster than the modulus
x % 2 != 0 //X plus or minus; Instead of saying x%2 is equal to 1, because if x is negative odd, x%2 is equal to negative 1
x & 0x1 == 0
2 switch two Numbers, no intermediate variables
void mySwap(int &a, int &b)
{
if(a == b) //You can get the right answer if you're equal, but you don't have to
return;
a ^= b;
b ^= a;
a ^= b;
}
Figure out the number of 1's in the binary representation of integers without shifting them one by one
int numOfBit1(int a)
{
int cnt = 0;
while(a != 0)
{
++cnt;
a &= a - 1; //Put the rightmost 1 as 0; Both positive and negative Numbers can be calculated, negative Numbers are calculated according to the complement, and the last sign bit is also counted
}
return cnt;
}
4 + / - conversion, no sign. Whether it's positive or negative, you just take the inverse and add 1
int a = 1;
a = ~a + 1; //A - 1
a = ~a + 1; //A becomes 1 again
Take the absolute value, no positive or negative, no sign, return the absolute value
int myAbs(int a)
{
int sign = a >> 31; //If a is positive, sign is 0; Otherwise sign is negative 1, which is 0xFFFFFFFF
return (a^sign) - sign; //A to the 0 minus 0 is a, a to the minus 1 minus minus 1 is minus a plus 1 is minus a, a to the minus 1 is minus a
}
Hope that this article is helpful for you C++ programming.