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.