Operator Signed Right Shift (>>) เลื่อนบิตของตัวเลขไปทางขวา จำนวนบิตที่ระบุ บิตขวาสุดจะหลุดออกไป และ คง Sign Bit (บิตซ้ายสุด) ไว้ เพื่อรักษาเครื่องหมาย (Signed)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Bitwise Right Shift Operator<br>");
document.write(-7 >> 1); // ผลลัพธ์: -4
</script>
</body>
</html>
การคำนวณ (-7 >> 1)
-7 (32-bit Two's Complement): 11111111111111111111111111111001 -7 >> 1 (Sign-propagating): 11111111111111111111111111111100 = -4
สมการทางคณิตศาสตร์
x >> n === Math.floor(x / (2 ** n)) สำหรับ Signed Integer
ตัวอย่างเพิ่มเติม
7 >> 1 // 3 (00000111 → 00000011) -7 >> 1 // -4 (Sign bit คงอยู่) 8 >> 2 // 2 -8 >> 2 // -2
ความแตกต่างกับ >>> (Zero-fill Right Shift)
| Operator | ชื่อ | บิตซ้ายสุด | ตัวอย่าง -7 >> 1 |
|---|---|---|---|
>> | Signed Right Shift | คง Sign Bit | -4 |
>>> | Zero-fill Right Shift | เติม 0 เสมอ | 2147483644 |
การใช้งาน: หาร 2^n แบบ Integer (Truncate ทศนิยม) สำหรับตัวเลขลบ ใช้ >> สำหรับ Unsigned ใช้ >>>