There are such expressions:
var x = 2 var y = 5 x^y выводит: 7 var x = 5 var y = 7 x^y выводит: 2 How is this calculated?
There are such expressions:
var x = 2 var y = 5 x^y выводит: 7 var x = 5 var y = 7 x^y выводит: 2 How is this calculated?
XOR is an exclusive OR logical operation. The result of performing a logical XOR operation will be equal to 1 if only one of the bits is 1, in all other cases, the result is 0. The truth table has the following form:
xyx^y 0 0 0 0 1 1 1 0 1 1 1 0 Take your example and for each bit according to the truth table we calculate the value of the result:
x = 2 // В двоичном виде это 010 y = 5 // В двоичном виде это 101 2 ^ 5 = 7 // В двоичном виде это 111 XOR is the addition operation modulo 2. It is calculated in the following examples: Let’s represent the numbers in binary form:
2 - 010 5 - 101 Then everything is simple, we look in pairs of bits, of each number, where there is only one unit in the pair, we write 1 to the result, otherwise 0. Look, from left to right:
0 and 1 - one, as a result of 1
1 and 0 - one unit, as a result of 1
0 and 1 one, resulting in 1
Total, again:
2 - 010 5 - 101 111 - 7 Second example:
5 - 101 7 - 111 010 - 2 Related Links:
Just as bitwise XOR:
var x = 2, y = 5, z = x ^ y; console.log("%d\n%d\n%d", x, y, z); x = ("0".repeat(31) + x.toString(2)).slice(-32); y = ("0".repeat(31) + y.toString(2)).slice(-32); z = ("0".repeat(31) + z.toString(2)).slice(-32); console.log("%s\n%s\n%s", x, y, z); z = (x+y).replace(/(.)(?=.{31}(.))/g, (m,a,b) => a==b ? 0 : 1).slice(0, 32); console.log(z); Conclusion:
2 5 7 00000000000000000000000000000010 00000000000000000000000000000101 00000000000000000000000000000111 00000000000000000000000000000111 Source: https://ru.stackoverflow.com/questions/517286/
All Articles