Languages
[Edit]
EN

JavaScript - bitwise XOR operator

5 points
Created by:
elmer
646

The main goal of this article is to show how bitwise XOR operation (^ operator, called: Exclusive OR) works on the JavaScript example.

The main concept of the bitwise XOR operation is to make XOR operations on each corresponding bits.

Quick solution:

 

The truth table for the XOR operation is: 

aba XOR b (in JavaScript: a ^ b)JS Example
0000 ^ 0 === 0
0110 ^ 1 === 1
1011 ^ 0 === 1
1101 ^ 1 === 0

So, the above table can be presented in JavaScript as:

 

More complex example

Edit

 

Bitwise XOR operation limitations

Edit

Hint: in JavaScript, bitwise XOR works on 32-bit integers. If number is bigger, the most significant bits are dicarded to get 32-bit integer number - it means only bits indexed from 0 to 31 will be used.

So, the above table can be also written as:

 

Features

Edit

1. bitwise XOR operation is fast - easy to do by any CPU.

2. bitwise XOR operation can be inverted - it means, we do not lose any information with that operation, e.g.

 

See also

Edit
  1. JavaScript - bitwise operators

  2. JavaScript - bitwise NOT example

  3. JavaScript - bitwise AND example

  4. JavaScript - bitwise OR example

  5. JavaScript - get supported max integer value

References

Edit
  1. Exclusive or (XOR) - Wikipedia
  2. Bitwise operation - Wikipedia

Alternative titles

  1. JavaScript - bitwise XOR (^) operator example
  2. JavaScript - exclusive OR
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join