### 2.16 Integer Bitwise Operators: ~, &, |, ^

A review of integer representation (p. 33) is recommended before continuing with this section on how integer bitwise operators can be applied to values of integral data types.

Integer bitwise operators include the unary operator ~ (bitwise complement) and the binary operators & (bitwise AND), | (bitwise inclusive OR), and ^ (bitwise exclusive OR, also known as bitwise XOR). The operators &, |, and ^ are overloaded, as they can be applied to boolean or Boolean operands to perform boolean logical operations (p. 78).

The binary bitwise operators perform bitwise operations between corresponding individual bit values in the operands. Unary numeric promotion is applied to the operand of the unary bitwise complement operator ~, and binary numeric promotion is applied to the operands of the binary bitwise operators. The result is a new integer value of the promoted type, which can be either int or long.

Given that A and B are corresponding bit values (either 0 or 1) in the left-hand and right-hand operands, respectively, these bitwise operators are defined as shown in Table 2.30. The operators are listed in order of decreasing precedence.

Table 2.30 Integer Bitwise Operators

Operator name | Notation | Effect on each bit of the binary representation |

Bitwise complement | ~A | Invert the bit value: 1 to 0, 0 to 1. |

Bitwise AND | A & B | 1 if both bits are 1; otherwise 0. |

Bitwise OR | A | B | 1 if either or both bits are 1; otherwise 0. |

Bitwise XOR | A ^ B | 1 if and only if one of the bits is 1; otherwise 0. |

The result of applying bitwise operators between two corresponding bits in the operands is shown in Table 2.31, where A and B are corresponding bit values in the left-hand and right-hand operands, respectively. Table 2.31 is analogous to Table 2.26 for boolean logical operators, if we consider bit value 1 to represent true and bit value 0 to represent false.

Table 2.31 Result Table for Bitwise Operators

A | B | Complement ~A | AND A & B | XOR A ^ B | OR A | B |

1 | 1 | 0 | 1 | 0 | 1 |

1 | 0 | 0 | 0 | 1 | 1 |

0 | 1 | 1 | 0 | 1 | |

0 | 0 | 1 | 0 | 0 | 0 |