Bitwise Operators
The bitwise operators of C a summarised in the following table:
Table: Bitwise operators
| & |
AND |
| | |
OR |
| ^ |
XOR |
| ~ |
One's Compliment |
| |
0 -> 1 |
| |
1 -> 0 |
| << |
Left shift |
| >> |
Right Shift |
DO NOT confuse & with &&: & is bitwise AND, && logical AND. Similarly for
and
.
is a unary operator -- it only operates on one argument to right of the operator.
The shift operators perform appropriate shift by operator on the right to the operator on the left. The right operator must be positive. The vacated bits are filled with zero (i.e. There is NO wrap around).
For example: x << 2 shifts the bits in x by 2 places to the left.
So:
if x = 00000010 (binary) or 2 (decimal)
then:
or 0 (decimal)
Also: if x = 00000010 (binary) or 2 (decimal)
or 8 (decimal)
Therefore a shift left is equivalent to a multiplication by 2.
Similarly a shift right is equal to division by 2
NOTE: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you want fast multiplications or division by 2 use shifts.
To illustrate many points of bitwise operators let us write a function, Bitcount, that counts bits set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.
int bitcount(unsigned char x)
{ int count;
for (count=0; x != 0; x>>=1);
if ( x & 01)
count++;
return count;
}
Bit Fields: Practical Example
This function illustrates many C program points:
- for loop not used for simple counting operation
- x
x = x >> 1
- for loop will repeatedly shift right x until x becomes 0
- use expression evaluation of x & 01 to control if
- x & 01 masks of 1st bit of x if this is 1 then count++