   Next: Bit Fields Up: Low Level Operators Previous: Low Level Operators

# Bitwise Operators

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:

• for loop not used for simple counting operation
• x x = x • 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++

Dave.Marshall@cm.cf.ac.uk
Fri May 20 13:40:49 BST 1994