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

JavaScript Bitwise Left Shift (<<) Operator คืออะไร?

Operator Bitwise Left Shift (<<) เลื่อนบิตของตัวเลขไปทางซ้าย จำนวนบิตที่ระบุ และเติม 0 ด้านขวา บิตซ้ายสุดจะหลุดออกไป (Discarded)

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

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

การคำนวณ

  7:       00000111
  7 << 1: 00001110  = 14  (7 × 2^1)
  7 << 2: 00011100  = 28  (7 × 2^2)
  7 << 3: 00111000  = 56  (7 × 2^3)

สมการทางคณิตศาสตร์

x << n === x * (2 ** n) (ภายในขอบเขต 32-bit Signed Integer)

การใช้งานทั่วไป

  • คูณ 2^n เร็ว: x << n เร็วกว่า x * Math.pow(2, n)
  • สร้าง Bit Mask: 1 << n สร้าง Mask ที่มีบิต n เป็น 1
  • Color Manipulation: (r << 16) | (g << 8) | b รวม RGB เป็น Integer
  • Permission Flags: const READ = 1 << 0; const WRITE = 1 << 1;

ข้อจำกัด: เลื่อนเกิน 31 บิต จะวนรอบ (Mod 32) เช่น 1 << 32 === 1