C++ Bitwise Operators


Bitwise operators in C++ are used to manipulate individual bits of integral data types (such as int and char). These operators perform operations at the bit level, making them useful for tasks that involve low-level data processing, such as graphics programming, encryption, and optimization. Below are the main bitwise operators in C++:

1. Bitwise AND (&)

The & operator performs a bitwise AND operation, which means each bit of the result is 1 if both corresponding bits in the operands are 1, otherwise, it's 0.

Example:

int a = 5; // 0101 in binary int b = 3; // 0011 in binary int result = a & b; // 0001 (1 in decimal)

2. Bitwise OR (|)

The | operator performs a bitwise OR operation. Each bit of the result is 1 if either or both corresponding bits in the operands are 1.

Example:

int a = 5; // 0101 in binary int b = 3; // 0011 in binary int result = a | b; // 0111 (7 in decimal)

3. Bitwise XOR (^)

The ^ operator performs a bitwise XOR operation. Each bit of the result is 1 if the corresponding bits in the operands are different; otherwise, it's 0.

Example:

int a = 5; // 0101 in binary int b = 3; // 0011 in binary int result = a ^ b; // 0110 (6 in decimal)

4. Bitwise NOT (~)

The ~ operator performs a bitwise NOT operation, inverting all bits (turning 0s into 1s and 1s into 0s).

Example:

int a = 5; // 0101 in binary int result = ~a; // 1010 (in a 4-bit representation, this is -6 in decimal due to two's complement)

5. Bitwise Left Shift (<<)

The << operator shifts the bits of the operand to the left by a specified number of positions, filling the empty bits with zeros.

Example:

int a = 5; // 0101 in binary int result = a << 1; // 1010 (10 in decimal)

6. Bitwise Right Shift (>>)

The >> operator shifts the bits of the operand to the right by a specified number of positions. For signed integers, the behavior depends on the system implementation (arithmetic vs logical shift).

Example:

int a = 5; // 0101 in binary int result = a >> 1; // 0010 (2 in decimal)

Use Cases

  • Bit Masking: Using bitwise AND to select specific bits in a number.
  • Flags: Using bitwise OR to set bits as flags.
  • Encryption and Hashing: Bitwise operations are often used for scrambling data.
  • Optimization: Bitwise operations are generally faster for certain arithmetic calculations.

These operators can be especially useful for scenarios where performance and efficient memory use are important.