Bitwise Operators
In C
, there are 6 bitwise operators.
Let's assume 2 variables
.
int a = 6;
int b = 2;
AND
int c = a & b; // (1)!
- Performs logical
AND
between2
(10
) and6
(110
), hence the result is2
(10
).
OR
int c = a | b; // (1)!
- Performs logical
OR
between2
(010
) and6
(110
), hence the result is6
(110
).
XOR
int c = a ^ b; // (1)!
- Performs logical
XOR
between2
(010
) and6
(110
), hence the result is4
(100
).
Left Shift
int c = a << 2; // (1)!
- Shifts the value of
a
(which is2
,10
inbinary
) towards left side by2
bits
. Hence the result is8
(1000
). After the shifting, the vacatedbits
are0
.
Right Shift
int c = a >> 1; // (1)!
- Shifts the value of
a
(which is2
,10
inbinary
) towards right side by1
bit
. Hence the result is1
(1
). After the shifting, the vacatedbits
are0
.
One's Complement
int c = ~a; // (1)!
- Flips the
bits
ofa
(2
=00000000000000000000000000000010
to11111111111111111111111111111101
which is-3
inbinary
).