C programming - bitwise XOR operator

http‮.www//:s‬theitroad.com

The bitwise XOR (exclusive OR) operator ^ in C programming is used to perform a bitwise XOR operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if the bits are different, and 0 if they are the same.

Here is an example of using the bitwise XOR operator:

#include <stdio.h>

int main() {
  int num1 = 5; // 101 in binary
  int num2 = 3; // 011 in binary
  int result = num1 ^ num2;

  printf("result = %d\n", result);

  return 0;
}

In this example, we declared two integer variables num1 and num2 and initialized them with the values 5 and 3, respectively. We used the bitwise XOR operator to perform a bitwise XOR operation between num1 and num2, and stored the result in the integer variable result. The binary representation of num1 is 101, and the binary representation of num2 is 011, so the result of the bitwise XOR operation is 110, which is equal to 6 in decimal.

The output of the program will be:

result = 6

The bitwise XOR operator is useful in situations where we need to flip specific bits in an integer. For example, we can use the bitwise XOR operator with a mask to flip specific bits of an integer.

#include <stdio.h>

int main() {
  int num = 0x0F; // 00001111 in binary
  int mask = 0x80; // 10000000 in binary
  int result = num ^ mask;

  printf("result = %d\n", result);

  return 0;
}

In this example, we declared an integer variable num and initialized it with the hexadecimal value 0x0F, which is equivalent to the binary value 00001111. We also declared an integer variable mask and initialized it with the hexadecimal value 0x80, which is equivalent to the binary value 10000000. We used the bitwise XOR operator to flip the most significant bit of num from 0 to 1. The result of the bitwise XOR operation is 10001111, which is equal to 143 in decimal.

The output of the program will be:

result = 143

In summary, the bitwise XOR operator ^ in C programming is used to perform a bitwise XOR operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if the bits are different, and 0 if they are the same. The bitwise XOR operator is useful in situations where we need to flip specific bits in an integer.