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.
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
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:
Table of Content
- Using String’s Character Codes and Bitwise Operators
- Leveraging Unicode Code Points and Conversion Methods
- Approach 3: Employing TextEncoder and Byte Conversion
- Approach 4: Using Array.from() and charCodeAt()