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:
Table of Content
Approach 1: Using String’s Character Codes and Bitwise Operators
- Character Code Extraction: To start, we’ll iterate through each character in the input string. For each character, we’ll extract its character code using the charCodeAt() method.
- Binary Conversion with Bitwise Operators: After obtaining the character code, we’ll convert it to its binary representation. We’ll achieve this by performing bitwise operations, using shifts and masks to extract individual bits and create the binary value.
- Grouping and Formatting: To ensure a consistent format, we’ll pad the binary representation with leading zeros to make it a complete byte (8 bits). We’ll then aggregate the padded binary values and separate them with spaces.
Example: This example shows the use of the above-explained approach.
Javascript
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); |
01000111 01000110 01000111
Approach 2: Leveraging Unicode Code Points and Conversion Methods
- Obtaining Code Points: We’ll traverse through each character within the input string and employ the codePointAt(0) method to fetch its corresponding Unicode code point.
- Binary Conversion: Similar to the preceding method, we’ll translate the Unicode code point into binary form using the toString(2) method.
- Padding and Grouping: As previously discussed, we’ll ensure the binary values are 8 bits long by adding padding, and then consolidate them with spaces.
Example: This example shows the use of the above-explained approach.
Javascript
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); |
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.
- Text Encoding: Employing the TextEncoder API, we’ll encode the input string into a sequence of bytes. This process effectively converts characters into their respective byte values.
- Byte-to-Binary Conversion: Subsequently, each byte is transformed into binary using the toString(2) method. This step ensures that each byte’s binary representation spans 8 bits consistently.
- Aggregation: The resulting binary values are combined, with spaces as separators, to compose the comprehensive binary representation of the input string.
Example: This example shows the use of the above-explained approach.
Javascript
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); }); |
01000111 01000110 01000111