Bitwise operations are operations that are performed in binary order. In a program, it is often necessary to deal with bits problems. The C + + language provides 6 bit operator operators. These operators can only be used for integer operands, that is, only for signed or unsigned char,short,int and long types.
In practice, it is recommended to use the unsigned integer operand because the signed operand may be different from the results of different machines.
C + + and C have the same bitwise operators, but C + + has added Bitset standard library to support bit set operations, please refer to http://book.51cto.com/art/200809/88698.htm or http:// Book.csdn.net/bookfiles/17/1001760.shtml, these links are "C + + Primer Chinese version" in the content, we can also read directly.
The following is a list of C + + bitwise operator operators, where the operator precedence is descending from top to bottom, but the <<,>> priority is the same.
C + + bitwise operator
Operator |
Function |
Usage |
~ |
-bit negation |
~expr |
<< |
Move left |
Expr1 << EXPR2 |
>> |
Move right |
Expr1 >> EXPR2 |
& |
Bit and |
Expr1 & EXPR2 |
^ |
Bit XOR or |
Expr1 ^ expr2 |
| |
Bit or |
Expr1 | Expr2 |
The code example is as follows:
Code
1 #include <iostream>
2 using namespace Std;
3 int main () {
4 unsigned short x=3,y=5;
5 cout<< "~x=" << (unsigned short) ~x<<endl;//bit negation
6 cout<< "~x=" <<~x<<endl;//bit to reverse
7 cout<< "x&y=" << (x&y) <<endl;//bit with
8 cout<< "x^y=" << (x^y) <<endl;//-XOR or
9 cout<< "x|y=" << (x|y) <<endl;//bit or
cout<< "x<<1=" << (x<<1) <<endl;//bit left-shift
One cout<< "y>>1=" << (y>>1) <<endl;//bit to the right
return 0;
13}
The result of the operation is as follows:
~x=65532
~x=-4
X&y=1
X^y=6
X|y=7
X<<1=6
y>>1=2
The code is explained as follows:
Short is a 16-bit integer, so the binary representation of the x,y is as follows:
X=3 (00000000 00000011)
Y=5 (00000000 00000101)
~ 00000000 00000011
= 11111111 11111100 (65532 or-4) (As for why the same number of bits is different, this is related to the computer's numeric representation, for specific reasons can search "complement")
00000000 00000011
& 00000000 00000101
= 00000000 00000001 (1)
00000000 00000011
^ 00000000 00000101
= 00000000 00000110 (6)
00000000 00000011
| 00000000 00000101
= 00000000 00000111 (7)
00000000 00000011<<1
= 00000000 00000110 (6)
00000000 00000101>>1
= 00000000 00000010 (2)
&= ^= |= These three operators are similar to + =, a &= b is a first and B, then assigns to a.