Operator
&
| & | 1 | 0 |
|---|---|---|
| 1 | 1 | 0 |
| 0 | 0 | 0 |
|
| \ | 1 | 0 |
|---|---|---|
| 1 | 1 | 1 |
| 0 | 1 | 0 |
^
| ^ | 1 | 0 |
|---|---|---|
| 1 | 0 | 1 |
| 0 | 1 | 0 |
~
~ 1 0 0 1 1
=> 0 1 1 0 0
<<
1 | int a = 8; |
>>
1 | unsigned int a = 8; |
Common Problem
Implement division
1
2
3int a = 2;
a >> 1; ---> 1
a << 1; ---> 4Swap two digits
1
2
3
4
5void swap(int &a, int &b) {
a ^= b;
b ^= a;
a ^= b;
}Explaination:
Step 1:a ^= b —-> a = (a^b);Step 2:b ^= a —-> b = b\^(a^b) —-> b = (b\^b)^a = a
Step 3:a ^= b —-> a = (a\^b)^a = (a\^a)^b = b
Odd or Even
If the last digit is 0, then even. Otherwise, odd1
2
3if(0 == (a & 1)) {
even
}Change the sign
1
2
3int reversal(int a) {
return ~a + 1;
}Detect opposite sign
1
2
3
4int oppositeSigns(int x, int y) {
// -1 if opposite, 0 if not
return ((x ^ y) >> 31);
}1
2
3
4int oppositeSigns(int x, int y) {
// 1 if opposite, 0 if not
return ((x ^ y) >>> 31);
}