The bitwise operators of C a summarised in the following table:
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: shifts the bits in by 2 places to the left.
So:
if (binary) or 2 (decimal)
then:
or 0 (decimal)
Also: if (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 count2 bits set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.
This function illustrates many C program points: