How does the bitwise XOR (^) operator work?
How does the bitwise XOR (^) operator work?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
31-Oct-2023The bitwise XOR (^) operator in JavaScript is used to perform an exclusive OR operation on the individual bits of two numbers. It returns a number where each bit is set (1) if the corresponding bits of the two numbers being XORed are different, and it sets the bit to 0 if the corresponding bits are the same.
Here's how the bitwise XOR operator works with a simple example:
In this example, the XOR operation is performed on num1 and num2. If the bits at the same positions in both numbers are different, the result has a 1 in that position; otherwise, it has a 0. So, 5 ^ 3 results in 6 because the bits in the binary representation differ at the 2^0 and 2^1 positions.
Remember that the XOR operator can be useful in various scenarios, such as swapping two values without using a temporary variable or toggling specific bits within a number.