Bitwise Operators in C

In C, bitwise operators are used to manipulate individual bits of data, often in integer types. These operators are useful in scenarios such as low-level system programming, optimizing code for performance, and working with hardware interfaces.

There are six bitwise operators in C:

  1. &: Bitwise AND
  2. |: Bitwise OR
  3. ^ : Bitwise XOR
  4. ~: Bitwise NOT
  5. <<: Left shift
  6. >>: Right shift

Bitwise AND (&)

The bitwise AND operator performs a logical AND operation on each pair of corresponding bits in two integers. It returns a value where each bit is set to 1 if and only if the corresponding bits in both operands are 1.

int a = 5; // Binary: 0101 int b = 3; // Binary: 0011 int result = a & b; // Binary result: 0001 (Decimal: 1)

Bitwise OR (|)

The bitwise OR operator performs a logical OR operation on each pair of corresponding bits in two integers. It returns a value where each bit is set to 1 if at least one of the corresponding bits in both operands is 1.

int a = 5; // Binary: 0101 int b = 3; // Binary: 0011 int result = a b; // Binary result: 0111 (Decimal: 7)

Bitwise XOR (^ )

The bitwise XOR (exclusive OR) operator performs an exclusive OR operation on each pair of corresponding bits in two integers. It returns a value where each bit is set to 1 if exactly one of the corresponding bits in both operands is 1.

int a = 5; // Binary: 0101 int b = 3; // Binary: 0011 int result = a ^ b; // Binary result: 0110 (Decimal: 6)

Bitwise NOT (~)

The bitwise NOT operator inverts each bit of an integer, turning 1s into 0s and 0s into 1s.

int a = 5; // Binary: 0101 int result = ~a; // Binary result: 1010 (Decimal: -6)

Left Shift (<<)

The left shift operator shifts the bits of an integer to the left by a specified number of positions. This effectively multiplies the integer by 2 raised to the power of the shift count.

int a = 5; // Binary: 0101 int result = a << 2; // Binary result: 010100 (Decimal: 20)

Right Shift (>>)

The right shift operator shifts the bits of an integer to the right by a specified number of positions. This effectively divides the integer by 2 raised to the power of the shift count (with truncation for integers).

int a = 20; // Binary: 010100 int result = a >> 2; // Binary result: 000101 (Decimal: 5)

Bitwise operators can be used in a variety of ways, such as:

  1. Manipulating low-level data structures, such as registers and memory
  2. Performing bit-level arithmetic
  3. Implementing cryptographic algorithms
  4. Compressing and decompressing data

Conclusion

Bitwise operators are often used for tasks such as setting and clearing individual bits, extracting information from bit fields, and implementing data compression algorithms. They are also used in low-level hardware interactions and optimizing code for performance. It's important to use them with care, as improper usage can lead to unexpected behavior or bugs.