Explain Codes LogoExplain Codes Logo

How do I convert an integer to binary in JavaScript?

javascript
number-conversions
bitwise-operations
javascript-quirks
Nikita BarsukovbyNikita Barsukov·Jan 6, 2025
TLDR

Here's how to convert an integer to binary in JavaScript using the toString(2) method:

let binaryString = (5).toString(2); // "101"

toString(2) transforms an integer into its binary string representation. Although simple for positive integers, negative and extremely large integers require extra care.

Managing negative integers

JavaScript utilizes two's complement for negative integers. To convert negative integers to binary:

function toBinaryString(num) { if (num >= 0) { return num.toString(2); } else { // Because negativity is inherently filled with shiftiness return (num >>> 0).toString(2); } } let binaryStringNeg = toBinaryString(-5); // "11111111111111111111111111111011"

This function checks if a given number is positive or negative and applies an appropriate conversion to binary.

Tackling large integers

BigInt comes to our rescue when managing large numbers or precision-critical numbers:

let bigNumber = BigInt("12345678901234567890"); let binaryStringBigInt = bigNumber.toString(2);

Before converting numbers to binary, it's a good idea to verify if the number falls within the safe integer range using Number.isSafeInteger(). This is critical when working with floating point numbers:

function isSafeToConvert(num) { // You're either in the safe zone, or you're not... Choose wisely! return Number.isSafeInteger(num); }

Formatting for human readability

For a uniform look, use String.prototype.padStart() to prepend leading zeros to binary values:

let binaryStringPadded = (5).toString(2).padStart(8, '0'); // "00000101"

This ensures a consistent length for all binary strings, improving both human readability and computational comparisons.

Beware the quirks of bitwise operations

In JavaScript, bitwise operations convert numbers into 32-bit integers before computation, potentially converting back after. This can lead to surprises when numbers overflow this size. Be alert and test meticulously.

Old browser? No problem!

For those targeting older browsers, you may need to implement polyfills for methods like padStart():

if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength, padString) { targetLength = targetLength >> 0; // Well, truncating sounded shorter than "coercing to a 32-bit int." padString = String(padString || ' '); if (this.length > targetLength) { return String(this); } else { targetLength = targetLength - this.length; if (targetLength > padString.length) { // If padString had a dollar for each repeat... It'd be rich! padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + String(this); } }; }

Diving deeper into number conversions

The MDN Web Docs offer a fantastic overview of number conversions and bitwise operators. A proper understanding of these topics greatly simplifies numeric conversions under various scenarios.

Historical answers and their comments can provide insights and alternative methods for handling edge cases - for instance, displaying 64-bit numbers in binary within the constraints of JavaScript.

Testing is not an option, but a necessity

As a good coding practice, test your solution with a variety of inputs, including:

  • Extremely large numbers.
  • Negative numbers.
  • Floating-point numbers, where precision is crucial.

With JavaScript's unique way of handling floating point representation and binary operations, it's always best to err on the side of caution.