First of all, we need to understand how the bitwise operator works.
Bitwise operators are kind of advanced - they work on the binary bits of numbers.
First, you have bitwise AND(&).
This compares each bit.
If the bits from both of the numbers are 1, then the resulting bit is 1.
Otherwise, the resulting bit is 0.
Next, you have bitwise OR(|).
If either bit is 1, then the resulting bit is 1.
Also, you have bitwise XOR(^).
If only one of the bits is 1, then the resulting bit is 1
(if both are 1, or neither are 1, then the resulting bit is 0).
The final bitwise operator is bitwise NOT (~).
This works on only one operand - it simply flips the bits.
Second, we need to know HOW they can be used.
One main function is the easy conversion of decimal values to binary and vice versa.
We can use two operations to perform a number conversion.
1. Bit-wise AND operation. To compare the bits one by one.
2. Bit-wise Right - Shift Operation. To divide the number by 2.
Depending on the no of bits in the system, we need an initial constant.
For 4-bit numbers, we use 8 (1000)
Each step, we divide this constant by 2 using bit-wise right shift operator >>.
8>>1 = 4
4>>1 = 2
2>>1 = 1
( Operandtoshift >> NoOfTimesDone )
|