📜  js xor - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:59.566000             🧑  作者: Mango

JS XOR - Javascript

Introduction

In Javascript, XOR is a bitwise operator that stands for "exclusive or". It operates on two input bits and returns a result based on the following truth table:

| Input 1 | Input 2 | Output | | ------- | ------- | ------ | | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 |

XOR is commonly used in programming for various purposes such as encryption, data masking, and checksums. This article will explain how XOR works in Javascript, and provide examples of its use.

Basic Syntax

The basic syntax for performing XOR in Javascript is as follows:

let result = operand1 ^ operand2;

Where operand1 and operand2 are two values to be XOR'd together.

Examples
Example 1: XOR To Toggle A Boolean

One common use case of XOR in Javascript is to toggle a boolean value. This is done by XORing the boolean variable with true or false.

let testBool = true;
testBool = testBool ^ true;
console.log(testBool); // Output: false

testBool = testBool ^ false;
console.log(testBool); // Output: true
Example 2: XOR to Encrypt A String

Another common use case of XOR in Javascript is to encrypt a string. This is done by XORing each character of the string with a secret key. Here is an example of how to encrypt a string using XOR:

const secretKey = "secret";
let message = "Hello, world!";
let encryptedMessage = "";

for (let i = 0; i < message.length; i++) {
  let charCode = message.charCodeAt(i) ^ secretKey.charCodeAt(i % secretKey.length);
  encryptedMessage += String.fromCharCode(charCode);
}

console.log(encryptedMessage); // Output: >J§,--/Jö-Ø(

This code uses a for loop to iterate over each character of the message, and XORs each character code with the corresponding character code of the secret key. The result is then converted back to a character using the String.fromCharCode() method.

Example 3: XOR to Checksum Data

Finally, XOR can be used to generate a simple checksum for data. This is done by XORing the bits of the data together and then returning the result.

function xorChecksum(data) {
  let checksum = 0;

  for (let i = 0; i < data.length; i++) {
    checksum ^= data.charCodeAt(i);
  }

  return checksum;
}

let testData = "Hello, world!";
console.log(xorChecksum(testData)); // Output: 27

This code defines a function called xorChecksum that takes in a string of data and returns a checksum. The function uses a for loop to XOR each character of the data together and return the result.

Conclusion

In conclusion, XOR is a useful operator in Javascript for performing bitwise operations. It can be used for a variety of purposes such as encryption, data masking, and checksums. By understanding how XOR works, you can use it to write more efficient and secure code.