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

Bitwise Operators ใน JavaScript: NOT, Left Shift, Right Shift

Bitwise Operators (ตัวดำเนินการระดับบิต)

1. Bitwise NOT (~)

กลับบิตทุกตัว (One's Complement) ~x = -x - 1

<script>
  document.write(~13); // -14
</script>

คำอธิบาย: 13 = 00001101 (8-bit) → NOT → 11110010 = -14 (Two's Complement)

2. Left Shift (<<)

เลื่อนบิตไปซ้าย เติม 0 ด้านขวา x << n = x * 2^n

<script>
  document.write(5 << 2); // 20
</script>

คำอธิบาย: 5 = 0101 → << 2 → 010100 = 20

3. Unsigned Right Shift (>>>)

เลื่อนบิตไปขวา เติม 0 ด้านซ้าย (Unsigned) x >>> n = Math.floor(x / 2^n) สำหรับจำนวนบวก

<script>
  document.write(5 >>> 2); // 1
</script>

คำอธิบาย: 5 = 0101 → >>> 2 → 0001 = 1

ตารางสรุป

Operatorชื่อตัวอย่างผลลัพธ์
~Bitwise NOT~13-14
<<Left Shift5 << 220
>>Signed Right Shift-5 >> 1-3
>>>Unsigned Right Shift-5 >>> 12147483645