C - Operator Bitwise Operators

Introduction

The bitwise operators operate on the bits in integer values.

There are six bitwise operators, as shown in the following table.

OperatorDescription
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise Exclusive OR (XOR) operator
~ Bitwise NOT operator, also called the 1's complement operator
>> Bitwise shift right operator
<< Bitwise shift left operator

All of Bitwise Operators only operate on integer types.

The ~ operator is a unary operator-it applies to one operand-and the others are binary operators.

The bitwise AND operator, &, combines the corresponding bits of its operands in such a way that if both bits are 1, the resulting bit is 1; otherwise, the resulting bit is 0.

Suppose you declare the following variables:

int x = 13;
int y = 6;
int z = x & y;                     // AND corresponding bits of x and y

z will have the value 4 (binary 100). This is because the corresponding bits in x and y are combined as follows:

x           0      0     0      0     1     1      0     1

y           0      0     0      0     0     1      1     0

x & y       0      0     0      0     0     1      0     0

The bitwise OR operator, |, results in 1 if either or both of the corresponding bits are 1; otherwise, the result is 0.

If you combine the same values of x and y using the | operator in a statement such as this:

int z = x | y; // OR the bits of x and y

the result would be as follows:

x           0       0       0      0       1       1        0       1

y           0       0       0      0       0       1        1       0

x | y       0       0       0      0       1       1        1       1

The value stored in z would therefore be 15 (binary 1111).

The bitwise XOR operator, ^, produces a 1 if both bits are different, and 0 if they're the same.

int z = x ^ y;                     // Exclusive OR the bits of x and y

This results in z containing the value 11 (binary 1011), because the bits combine as follows:

x          0       0       0      0      1       1       0       1

y          0       0       0      0      0       1        1      0

x ^ y      0       0       0      0      1       0        1      1

The unary operator, ~, flips the bits of its operand, so 1 becomes 0, and 0 becomes 1.

You can apply this operator to x with the value 13:

int z = ~x;  // Store 1's complement of x

After executing this statement, z will have the value 14. The bits are set as follows:

x          0       0       0      0      1       1       0       1

~x          1      1       1      1      0       0        1      0

Related Topics

Exercise