Sling Academy
Home/JavaScript/JavaScript: Convert a String to Binary (2 Approaches)

JavaScript: Convert a String to Binary (2 Approaches)

Last updated: June 14, 2023

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!

Next Article: JavaScript: Remove non-alphanumeric characters from a string

Previous Article: JavaScript: Convert a byte array to a hex string and vice versa

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration