First, the basic operation
1.a<<b
A b-bit binary left, not enough to fill the place with a 0 bit
E.g
100<<2 == 10000
2.a>>b
A binary right shift bit b
E.g
100>>2 == 1
3.a|b
Or operations (bitwise OR), the same as long as there is a one-bit or two result is a 1, the result is all 0 0
4.a&b
Operation (bitwise AND), as long as the same bit is 1, the result is 1, a is 0 if a is 0 or 1, the result is zero.
5.a^b
XOR, as long as the same bit a 0 a 1, the result is 1; the same binary 0, the result is the same.
Second, advanced operation
1. Rapid Evaluation 2 ^ n
1<<n == pow(2,n)
Principle: 1 << n mean n-bit binary 1 is shifted to the left, then this number in binary form into a 100000 ... 000 (n zeros), exactly 2 ^ n
2. Analyzing odd and even
n & 1 == 1 was odd
n & 1 == 0, compared with the even
Principle: mean n & 1 and n is 1, then n and 1, 1 in addition to the right bit is 1 other bits are 0, by the result of the operation must be obtained in other bits are 0.
So the final result only the right end position 1 and the right bit of n is about, we know that the right bit 1 is 1, n right-most bit only to 1 when the result of 1 and operation is 1; n is right only when the bit is 0 and 1 with the operation result is zero.
Obviously the right bit binary 1 when the number is an odd number, the number is 0 is an even number, it is proved.
3.lowbit
a & (- a) represents the last digit of a binary.
Principle: involves knowledge complement binary, interested people can understand themselves.
Third, high-level operating
1.a >> b & 1 represents b if the first bit is a 1 True
Used to determine a bit binary
Principle: a b-bit left, then a right-most bit is the first of a b-bit original, and then do the arithmetic 1 (1 of 0 has no effect on the left was operational nature) can learn this bit is 1 or 0 (1 & 1 == 1,0 | 1 == 0)
2.a | (1 << n) represents a binary the n-th bit is set to 1
Principle: 1 << n can be considered as a binary number of 1 and consisting of n 0, where 0 part by the nature or the (0 | 0 == 0,1 | 0 == 1) does not know the binary bit impact.
1 is a partially or properties of (1 | 1 == 1,0 | 1 = 1) can be derived must be 1.