TIL the XOR operator in Javascript
POSTED ON:
TAGS: javascript math
The bitwise XOR operator (^) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s.
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).
const a = 5; // 00000000000000000000000000000101
const b = 3; // 00000000000000000000000000000011
console.log(a ^ b); // 00000000000000000000000000000110
// expected output: 6
I haven't really found real good use-cases of why a person would use it.
As noted in a comment, "XOR is a pretty neat party trick."
But it's used in Cryptographic algorithms.
XOR is used in cryptography for two main reasons: it is reversible e.g if A xor with B results in C then A xor with C will give B. it makes equal probability of 0 and 1 unlike AND & OR. if AND is used, there are 75% chances of output 0 and 25% of 1,if OR is used, there are 75% chances of output 1 and 25% of 0 so '1' and '0' output is not uniformly distributed and thus will not create randomness.
https://security.stackexchange.com/a/220699
MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR
Related TILs
Tagged: javascript