Bitwise Operators ( &, |, ^, ~, <<, >> )
Bitwise operators modify variables considering the bit patterns that represent the values they store.
operator | asm equivalent | description |
& |
AND |
Bitwise AND 位與
|
| |
OR |
Bitwise Inclusive OR 位或
|
^ |
XOR |
Bitwise Exclusive OR
異或,即
參與運算的位不同時其結果是1,否則結果為0 。即“相同為0,不同為1”
|
~ |
NOT |
Unary complement (bit inversion) 取反
|
<< |
SHL |
Shift Left 左移
|
>> |
SHR |
Shift Right 右移
|
從右開始為0位:
7 6 5 4 3 2 1 0
位與:將某位置為0
位或:將某位置為1
4的二進制:0b'100'
將x的2位置為0,其它位保留不變.
int x=7; //0b'111'
x &=~4; //結果:0b'011'
位或:
將x的第2位置為1,其它位保留不變.
int x= 9; //0b'1001'
x |= 4; //0b'1101'
There is an established order with the priority of each operator, the priority order is as follows:
Level | Operator | Description | Grouping |
1 |
:: |
scope |
Left-to-right |
2 |
() [] . -> ++ --
dynamic_cast static_cast reinterpret_cast const_cast typeid |
postfix |
Left-to-right |
3 |
++ -- ~ ! sizeof new delete |
unary (prefix) |
Right-to-left |
* & |
indirection and reference (pointers) |
+ - |
unary sign operator |
4 |
(type) |
type casting |
Right-to-left |
5 |
.* ->* |
pointer-to-member |
Left-to-right |
6 |
* / % |
multiplicative |
Left-to-right |
7 |
+ - |
additive |
Left-to-right |
8 |
<< >> |
shift |
Left-to-right |
9 |
< > <= >= |
relational |
Left-to-right |
10 |
== != |
equality |
Left-to-right |
11 |
& |
bitwise AND |
Left-to-right |
12 |
^ |
bitwise XOR |
Left-to-right |
13 |
| |
bitwise OR |
Left-to-right |
14 |
&& |
logical AND |
Left-to-right |
15 |
|| |
logical OR |
Left-to-right |
16 |
?: |
conditional |
Right-to-left |
17 |
= *= /= %= += -= >>= <<= &= ^= |= |
assignment |
Right-to-left |
18 |
, |
comma |
Left-to-right |