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

วิธีแปลง Decimal เป็น Binary ใน JavaScript

ใช้เมธอด .toString(2) ของ Number เพื่อแปลงเป็น Binary String รองรับทั้ง Positive และ Negative Numbers

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

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write("Decimal to Binary<br>");
      // Technique: Zero-fill Right Shift (>>>) 0 เพื่อแปลงเป็น Unsigned 32-bit
      document.write((-7 >>> 0).toString(2)); // ผลลัพธ์: "11111111111111111111111111111001"
    </script>
  </body>
</html>

วิธีการต่างๆ

วิธีCodeผลลัพธ์ (-7)หมายเหตุ
toString(2)(-7).toString(2)"-111"Signed Binary (มีเครื่องหมายลบ)
>>> 0 + toString(2)(-7 >>> 0).toString(2)"111...1001" (32 1's)Unsigned 32-bit Two's Complement
Number.toString(2)Number(-7).toString(2)"-111"เหมือนข้างบน

ฟังก์ชันสำเร็จรูป

function toBinary(num, bits = 32) {
  if (num >= 0) return num.toString(2).padStart(bits, '0');
  // Negative: Two's Complement
  return (num >>> 0).toString(2);
}

console.log(toBinary(7));    // "00000000000000000000000000000111"
console.log(toBinary(-7));   // "11111111111111111111111111111001"
console.log(toBinary(255));  // "00000000000000000000000011111111"

หมายเหตุ: JavaScript ใช้ IEEE 754 Double แต่ Bitwise Operators แปลงเป็น 32-bit Signed Integer ก่อนคำนวณ