Bit wise Operation

Bitwise Operations in C

Bitwise operations in C are used to manipulate individual bits of data. These operations work at the binary level, allowing you to perform operations such as setting, clearing, or toggling specific bits in a binary number. There are several bitwise operators available in C:

  1. Bitwise AND (&): Performs a bitwise AND operation between two operands. The result is 1 if both corresponding bits are 1, otherwise, it is 0.

  2. Bitwise OR (|): Performs a bitwise OR operation between two operands. The result is 1 if at least one of the corresponding bits is 1, otherwise, it is 0.

  3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation between two operands. The result is 1 if the corresponding bits are different, otherwise, it is 0.

  4. Bitwise NOT (~): Performs a bitwise NOT operation on a single operand. It flips each bit, turning 0s into 1s and 1s into 0s.

  5. Left Shift (<<): Shifts the bits of the left operand to the left by a specified number of positions. Zeros are shifted in from the right, and the leftmost bits are discarded.

  6. Right Shift (>>): Shifts the bits of the left operand to the right by a specified number of positions. For unsigned types, zeros are shifted in from the left. For signed types, the sign bit is shifted in from the left, which preserves the sign of the number.

Example:

Let's consider an example to illustrate the bitwise operations in C. Suppose we have two variables a and b with the following binary representations:

a = 10101010
b = 11001100
  1. Bitwise AND (&):
  2. a & b performs a bitwise AND operation between a and b.
  3. The result is 10001000.

  4. Bitwise OR (|):

  5. a | b performs a bitwise OR operation between a and b.
  6. The result is 11101110.

  7. Bitwise XOR (^):

  8. a ^ b performs a bitwise XOR operation between a and b.
  9. The result is 01100110.

  10. Bitwise NOT (~):

  11. ~a performs a bitwise NOT operation on a.
  12. The result is 01010101.

  13. Left Shift (<<):

  14. a << 2 shifts the bits of a two positions to the left.
  15. The result is 101010000.

  16. Right Shift (>>):

  17. b >> 3 shifts the bits of b three positions to the right.
  18. The result is 00011001.

These are the basic bitwise operations in C. They are commonly used in low-level programming, such as manipulating hardware registers or working with binary data.