Bitwise
Bitwise
1. The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two num
The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.
5. The >> (right shift) in C or C++ takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C or C++ takes one number and inverts all bits of it.
de <iostream>
namespace std;
in() {
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;
return 0;
b=9
=1
= 13
= 12
dd occurring element is 90
Complexity: O(n)
ary Space: O(1)
de <iostream>
namespace std;
in()
int x = 2, y = 5;
(x & y) ? cout <<"True " : cout <<"False ";
(x && y) ? cout <<"True " : cout <<"False ";
return 0;
True
Complexity: O(1)
ary Space: O(1)
eft-shift and right-shift operators are equivalent to multiplication and division by 2 respectively. As
oned in point 1, it works only if numbers are positive.
de <iostream>
namespace std;
in() {
operator should be used carefully. The result of ~ operator on a small number can be a big number if t
is stored in an unsigned variable. And the result may be a negative number if the result is stored in a sign
le (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the si
ude <iostream>
namespace std;
in() {
unsigned int x = 1;
signed int a = 1;
return 0;
d Result -2
ned Result 4294967294
Complexity: O(1)
ary Space: O(1)