How can I convert a number to a binary string in JavaScript?
Davide S
davide s profile pic

In JavaScript, you can convert a number to a binary string representation using thetoString() method and specifying the base as 2. Here's how you can accomplish this:

1
2
3

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

In this example,number.toString(2) converts thenumber to a binary string representation. The resultingbinaryString will contain the binary representation of the number as a string. If you want to ensure that the binary string has a specific number of bits, you can use thepadStart() method to add leading zeros:

1
2
3

const number = 42;
const binaryString = number.toString(2).padStart(8, '0');

In this case,binaryString will be a string with a length of 8 characters, filled with leading zeros to ensure a consistent number of bits. Keep in mind that thetoString() method converts the number to a string in the specified base, including binary. The resulting binary string will contain only0 and1 characters. It's worth noting that the binary string representation is useful for certain operations like bitwise operations or when working with binary data. However, for general purpose usage, you typically work with numbers in their numeric form and convert them to a binary string representation as needed.