Open In App

JavaScript Program to Convert a String to Binary

In this article, we will learn how to convert a string to binary in JavaScript. Binary representation holds special importance, especially in the realms of cryptography, low-level tasks, and other diverse programming situations.

Below are the following approaches to convert a string to binary in JavaScript:



Approach 1: Using String’s Character Codes and Bitwise Operators

Example: This example shows the use of the above-explained approach.




function convertToBinaryUsingCharacterCodes(input) {
    let binaryResult = '';
      
    for (let i = 0; i < input.length; i++) {
        const charCode = input.charCodeAt(i);
        let binaryValue = '';
          
        for (let j = 7; j >= 0; j--) {
            binaryValue += (charCode >> j) & 1;
        }
          
        binaryResult += binaryValue + ' ';
    }
      
    return binaryResult.trim();
}
  
const inputString = "GFG";
const binaryRepresentation = 
    convertToBinaryUsingCharacterCodes(inputString);
console.log(binaryRepresentation);

Output

01000111 01000110 01000111

Approach 2: Leveraging Unicode Code Points and Conversion Methods

Example: This example shows the use of the above-explained approach.




function convertToBinaryApproach2(input) {
    let binaryResult = '';
  
    for (const char of input) {
        const codePoint = char.codePointAt(0);
        const binaryValue = codePoint.toString(2);
        binaryResult += 
            binaryValue.padStart(8, '0') + ' ';
    }
  
    return binaryResult.trim();
}
  
const inputString = "GFG";
const binaryRepresentation = 
      convertToBinaryApproach2(inputString);
console.log(binaryRepresentation);

Output
01000111 01000110 01000111

Approach 3: Employing TextEncoder and Byte Conversion

This strategy leverages the TextEncoder API, which encodes strings into bytes and then transforms these bytes into binary representation.

Example: This example shows the use of the above-explained approach.




async function convertToBinaryApproach3(input) {
    const encoder = new TextEncoder();
    const encodedData = encoder.encode(input);
    const binaryResult = 
        [...encodedData].map(byte => byte.toString(2)
            .padStart(8, '0')).join(' ');
    return binaryResult;
}
  
const inputString = "GFG";
convertToBinaryApproach3(inputString)
    .then(binaryRepresentation => {
        console.log(binaryRepresentation);
    })
    .catch(error => {
        console.error(error);
    });

Output
01000111 01000110 01000111

Article Tags :