How do I convert an integer to binary in JavaScript?

Learn how do i convert an integer to binary in javascript? with practical examples, diagrams, and best practices. Covers javascript, numbers development techniques with visual explanations.

Converting Integers to Binary in JavaScript

Converting Integers to Binary in JavaScript

Learn various methods to convert decimal integers into their binary string representation in JavaScript, from built-in functions to manual bitwise operations.

Converting an integer to its binary representation is a common task in programming, especially when dealing with bitwise operations, data transmission, or low-level manipulations. JavaScript provides several straightforward ways to achieve this, ranging from using built-in Number methods to implementing custom algorithms. This article will explore the most common and efficient techniques, complete with code examples and explanations.

Using the toString() Method

The simplest and most common way to convert a number to a binary string in JavaScript is by using the toString() method of the Number prototype. This method accepts an optional argument, radix, which specifies the base to use for representing numeric values. For binary conversion, you'll pass 2 as the radix.

const decimalNumber = 42;
const binaryString = decimalNumber.toString(2);

console.log(binaryString); // Output: "101010"

const anotherNumber = 255;
console.log(anotherNumber.toString(2)); // Output: "11111111"

Converting a decimal number to binary using toString(2).

Handling Negative Numbers

The toString(2) method provides the binary representation of the absolute value of negative numbers, prefixed with a minus sign. If you need a two's complement representation, which is common in computer science for signed integers, you'll need a different approach, often involving bitwise operations.

const negativeNumber = -42;
const binaryStringNegative = negativeNumber.toString(2);

console.log(binaryStringNegative); // Output: "-101010"

The toString(2) method for negative numbers.

A flowchart diagram illustrating the process of converting a positive integer to binary using the toString(2) method. Start node 'Input Decimal Number', followed by 'Call .toString(2)', then 'Return Binary String'. Clear, simple arrows connect the steps.

Process flow for positive integer to binary using toString(2).

Two's Complement for Negative Numbers

To get the two's complement binary representation of a negative number, you typically work with a fixed bit length (e.g., 32-bit for JavaScript's standard integer operations). You can achieve this using bitwise operators, which treat numbers as 32-bit signed integers.

function toTwosComplementBinary(num, bits) {
  if (num >= 0) {
    return num.toString(2).padStart(bits, '0');
  } else {
    // Use bitwise OR with 0 to ensure 32-bit signed integer behavior
    // Then use `>>> 0` to convert to unsigned 32-bit and get binary
    return (num >>> 0).toString(2).padStart(bits, '0');
  }
}

console.log(toTwosComplementBinary(42, 8));    // Output: "00101010"
console.log(toTwosComplementBinary(-42, 8));   // Output: "11010110" (8-bit two's complement)
console.log(toTwosComplementBinary(-42, 32));  // Output: "11111111111111111111111111010110"

Custom function for two's complement binary representation.