C Bitwise XOR Assignment Operator
In C, the Bitwise XOR Assignment ^= operator is a compound assignment operator that performs a bitwise XOR operation between two operands and assigns the result to the left operand.
Bitwise XOR Assignment operator is useful for toggling bits in a variable efficiently.
Syntax of the Bitwise XOR Assignment Operator
The syntax to use the Bitwise XOR Assignment operator is:
variable ^= value;
Explanation:
variable: The left operand whose bits will be XORed.^=: The Bitwise XOR Assignment operator.value: The right operand whose bits are XORed withvariable.- Return Value: The operator returns the updated value of
variableafter the XOR operation.
Examples of the Bitwise XOR Assignment Operator
1. Using XOR Assignment on Two Integers
In this example, we will use the ^= operator to perform a bitwise XOR operation on two integers and print the result.
main.c
#include <stdio.h>
int main() {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
a ^= b; // a = a ^ b
printf("Result after XOR Assignment: %d\n", a);
return 0;
}
Explanation:
- We declare two integer variables
aandbwith values 5 and 3. - The binary representation of
ais0101andbis0011. - The expression
a ^= bis equivalent toa = a ^ b. - The XOR operation results in
0110(decimal 6), which is assigned back toa.
Output:
Result after XOR Assignment: 6
2. Using XOR Assignment to Toggle a Bit
In this example, we will use the ^= operator to toggle a specific bit in an integer.
main.c
#include <stdio.h>
int main() {
int num = 6; // Binary: 0110
int mask = 2; // Binary: 0010
num ^= mask; // Toggle the second bit
printf("Number after bit toggle: %d\n", num);
return 0;
}
Explanation:
- We initialize
numwith the value 6 (binary0110). - We define
maskas 2 (binary0010), which represents the bit we want to toggle. - The operation
num ^= maskflips the second bit ofnum. - The resulting value of
numis0100(decimal 4).
Output:
Number after bit toggle: 4
3. Swapping Two Numbers Using XOR Assignment
In this example, we will use the ^= operator to swap two numbers without using a temporary variable.
main.c
#include <stdio.h>
int main() {
int x = 10, y = 20;
x ^= y;
y ^= x;
x ^= y;
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
Explanation:
- We initialize two integers
xandywith values 10 and 20. - The first XOR operation
x ^= ystores the XOR result inx. - The second XOR operation
y ^= xextracts the original value ofxand stores it iny. - The third XOR operation
x ^= yextracts the original value ofyand stores it inx. - As a result,
xandyare swapped without using a temporary variable.
Output:
After swapping: x = 20, y = 10
Conclusion
In this tutorial, we explored the Bitwise XOR Assignment ^= operator in C:
- The
^=operator performs a bitwise XOR between two values and assigns the result to the left operand. - It is useful for toggling bits, performing XOR-based operations, and swapping values.
- The return value of
^=is the updated value of the left operand.
