JavaScript Bitwise Operators จัดการตัวเลขเป็นลำดับ 32-bit Signed Integer (Two's Complement) นี่คือรายการ Operator ทั้ง 7 ตัว:
| ลำดับ | Operator & ชื่อ | คำอธิบาย |
|---|---|---|
| 1 | & Bitwise AND | ทั้งคู่เป็น 1 → 1 |
| 2 | | Bitwise OR | บิตไหนบิตหนึ่งเป็น 1 → 1 |
| 3 | ^ Bitwise XOR | บิตต่างกัน (0-1 หรือ 1-0) → 1 |
| 4 | ~ Bitwise NOT | กลับบิตทั้งหมด (0↔1) |
| 5 | << Left Shift | เลื่อนบิตซ้าย เติม 0 ด้านขวา |
| 6 | >> Signed Right Shift | เลื่อนบิตขวา คง Sign Bit |
| 7 | >>> Zero-fill Right Shift | เลื่อนบิตขวา เติม 0 ด้านซ้าย |
ตัวอย่าง Bitwise OR (|)
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Bitwise OR Operator<br>");
// 7 = 00000000000000000000000000000111
// 1 = 00000000000000000000000000000001
document.write(7 | 1); // ผลลัพธ์: 7
</script>
</body>
</html>
ข้อสังเกตสำคัญ
- JavaScript แปลง Operand เป็น 32-bit Integer ก่อนคำนวณเสมอ
- ผลลัพธ์ก็เป็น 32-bit Signed Integer (-2,147,483,648 ถึง 2,147,483,647)
- ใช้กับ Number เท่านั้น ไม่ทำงานกับ BigInt ต้องใช้ BigInt Bitwise Operators แทน