JavaScript: Convert a String to Binary (2 Approaches)

Updated: June 14, 2023 By: Khue Post a comment

Binary refers to the representation and manipulation of data using the base-2 number system, which uses only 0s and 1s. It is used for bitwise operations, handling binary data, and working with flags or binary flags in programming.

This concise, example-based article will walk you through a couple of different ways to convert a given string into binary codes in JavaScript.

Using the charCodeAt() and the toString() methods

The main idea of this approach is to convert each character of the input string to its Unicode code point using charCodeAt(), then converts the code point to binary using toString(2).

The detailed steps are:

  1. Iterate over each character in the string.
  2. Convert the character’s Unicode code point to binary by calling charCodeAt().toString(2).
  3. Pad the binary representation with leading zeros if needed.
  4. Concatenate the binary representations of all characters to form the binary string.

Code example:

const stringToBinary = (str) => {
  let binary = '';
  for (let i = 0; i < str.length; i++) {
    const charBinary = str[i].charCodeAt().toString(2);

    // Pad with leading zeros to ensure 8-bit representation
    binary += charBinary.padStart(8, '0');
  }
  return binary;
};

// Example usage
const inputString = 'www.slingacademy.com';
const binaryString = stringToBinary(inputString);
console.log(binaryString);

Output:

0111011101110111011101110010111001110011011011000110100101101110011001110110000101100011011000010110010001100101011011010111100100101110011000110110111101101101

Performance: This approach has a time complexity of O(n), where n is the length of the input string.

Using TextEncoder and Uint8Array

In this approach, we will use the TextEncoder API to encode the string into bytes and then convert each byte to binary using Uint8Array and toString(2).

The process can be described explicitly in the following steps:

  1. Create a TextEncoder instance.
  2. Encode the string into bytes using encode().
  3. Iterate over the encoded bytes.
  4. Convert each byte to binary using Uint8Array and toString(2).
  5. Pad the binary representation with leading zeros if needed.
  6. Concatenate the binary representations of all bytes to form the binary string.

Code example:

const stringToBinary = (str) => {
  const encoder = new TextEncoder();
  const bytes = encoder.encode(str);
  let binary = '';
  for (let i = 0; i < bytes.length; i++) {
    const byteBinary = bytes[i].toString(2);

    // Pad with leading zeros to ensure 8-bit representation
    binary += byteBinary.padStart(8, '0'); 
  }
  return binary;
};

// Example usage
const inputString = 'www.slingacademy.com';
const binaryString = stringToBinary(inputString);
console.log(binaryString);

Output:

0111011101110111011101110010111001110011011011000110100101101110011001110110000101100011011000010110010001100101011011010111100100101110011000110110111101101101

Performance: This solution has a time complexity of O(n), where n is the length of the input string. It leverages native encoding capabilities, which can provide efficient and reliable conversion. However, you need to write some extra lines of code (not so many).

The tutorial ends here. If you have any questions, please comment. Happy coding & have a nice day!