The “bitwise operators,” listed in Table 6.5, manipulate bits in data of the
integer type. These operators are often used in programs that must interact with
hardware.
Table 6.5 Bitwise Operators
Operator | Description |
~ | Complement |
<< | Left shift |
>> | Right shift |
& | AND |
^ | Exclusive OR |
| | Inclusive OR |
The ~ operator, known as the “one's complement,” acts on only one value (rather than on two, as do most operators). This operator changes every 1 bit in its operand to a 0 bit and vice versa.
The << and >> operators, known as the “shift operators,” shift the left operand by the value given in the right operand. These operators offer a fast, convenient way to multiply or divide integers by a power of 2.
The & operator, known as the “bitwise AND,” sets a bit to 1 if either of the corresponding bits in its operands is 1, or to 0 if both corresponding bits are 0. It is often used to “mask,” or turn off, one or more bits in a value.
The ^ operator, known as the “bitwise exclusive OR,” sets a bit to 1 if the corresponding bits in its operands are different, or to 0 if they are the same.
The | operator, known as the “bitwise inclusive OR,” sets a bit to 1 if either of the corresponding bits in its operands is 1, or to 0 if both corresponding bits are 0. It is often used to turn on bits in a value.
Each of the bitwise operators is used in the BITWISE.C program, shown below.
/* BITWISE.C: Demonstrate bitwise operators. */
#include <stdio.h>
main()
{
printf( "255 & 15 = %d\n", 255 & 15 );
printf( "255 | 15 = %d\n", 255 | 15 );
printf( "255 ^ 15 = %d\n", 255 ^ 15 );
printf( "2 << 2 = %d\n", 2 << 2 );
printf( "16 >> 2 = %d\n", 16 >> 2 );
printf( "~2 = %d\n", ~2 );
}
The output from BITWISE.C,
255 & 15 = 15
255 | 15 = 255
255 ^ 15 = 240
2 << 2 = 8
16 >> 2 = 4
~2 = -3
shows the results of the program's various bitwise operations.
The fourth and fifth output lines show you how to use shift operators to multiply and divide by powers of 2. The program multiplies 2 by 4 by shifting the value 2 twice to the left:
2 << 2 = 8
Similarly, the program divides 16 by 4 by shifting the value 16 twice to the right:
16 >> 2 = 4