Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript Bitwise XOR (^) Operator คืออะไร?

Operator Bitwise XOR (^) ย่อมาจาก Exclusive OR เปรียบเทียบบิตคู่ต่อคู่ ผลลัพธ์เป็น 1 ก็ต่อเมื่อบิตต่างกัน (0 และ 1 หรือ 1 และ 0) หากเหมือนกัน (0-0 หรือ 1-1) จะได้ 0

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write("Bitwise XOR Operator<br>");
      // 7 = 00000000000000000000000000000111
      // 1 = 00000000000000000000000000000001
      document.write(7 ^ 1); // ผลลัพธ์: 6
    </script>
  </body>
</html>

การคำนวณ

  7:  00000111
  1:  00000001
  -------------
  7^1: 00000110  = 6

คุณสมบัติพิเศษของ XOR

  • Self-inverse: a ^ b ^ b === a (XOR เดียวกัน 2 ครั้ง กลับค่าเดิม)
  • a ^ 0 === a
  • a ^ a === 0
  • a ^ b === b ^ a (Commutative)

การใช้งานจริง

  • Swap ตัวแปรไม่ต้อง Temp: a ^= b; b ^= a; a ^= b;
  • Toggle Flag: flags ^= MASK (สลับ On/Off)
  • Simple Encryption/Obfuscation: XOR กับ Key
  • Parity Check / Checksum: XOR ทุก Byte
  • หาค่าที่ซ้ำไม่ได้ใน Array: arr.reduce((a, b) => a ^ b) (ถ้ามีคู่ให้เหลือตัวเดี่ยว)

แก้ไขข้อมูลต้นฉบับ: คำอธิบายเดิมเขียนว่า "If both the bits are different, then 1 is returned when Bitwise OR (|) operator is used" — ผิด ควรเป็น XOR (^) ไม่ใช่ OR (|)