Explain how XOR (^) bit operator works
Explain how XOR (^) bit operator works
The XOR (exclusive OR) bitwise operator, denoted by the caret symbol (^), is a binary operator that performs a logical exclusive OR operation on each pair of corresponding bits of two operands. The result of the XOR operation is 1 if the corresponding bits of the operands are different, and 0 if they are the same.
Basic Operation:
The truth table for XOR is as follows:
x | y | x ^ y |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Example:
Consider the numbers 5 (binary 0101) and 3 (binary 0011).
Performing XOR on these numbers:
0101 (5)
^ 0011 (3)
------
0110 (6)
The result is 6 (binary 0110) because the bits differ in the second and third positions.
Properties of XOR:
Applications:
function swapWithXOR(a, b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log("a: " + a + ", b: " + b);
}
swapWithXOR(4, 1); // a: 1, b: 4
-4: 1000 0100 (binary), two's complement: 1111 1100
-2: 1000 0010 (binary), two's co...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào