JavaScript Program to Convert a String to Binary
Last Updated :
10 Jul, 2024
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:
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);
Output01000111 01000110 01000111
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);
Output01000111 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);
});
Output01000111 01000110 01000111
Using Array.from() and charCodeAt()
In this approach, we utilize the Array.from() method to create an array of characters from the input string. Then, we apply the charCodeAt() method to each character to obtain its Unicode code point. Finally, we convert each Unicode code point to its binary representation using the toString(2) method.
JavaScript
function stringToBinaryWithArrayFrom(str) {
return Array.from(str, char => char.charCodeAt(0).toString(2).padStart(8, '0')).join(' ');
}
console.log(stringToBinaryWithArrayFrom("GFG"));
Output01000111 01000110 01000111
Using TextDecoder and Uint8Array
The TextEncoder encodes a string into a Uint8Array of bytes. Each byte is then converted to its binary representation using `toString(2)`, and padded to 8 bits. The binary values are joined with spaces, resulting in the binary representation of the input string.
Example:
JavaScript
function stringToBinaryUint8Array(str) {
const encoder = new TextEncoder();
const encoded = encoder.encode(str);
const binaryArray = Array.from(encoded).map(byte => {
return byte.toString(2).padStart(8, '0');
});
return binaryArray.join(' ');
}
console.log(stringToBinaryUint8Array("Hello"));
Output01001000 01100101 01101100 01101100 01101111
Using Base64 Encoding and Conversion
In this approach, we will convert the string to a binary representation by first encoding the string to Base64 format. Then, we will convert each Base64 character to its binary form, ensuring that the final binary representation is accurate.
Steps:
- Base64 Encoding: Use JavaScript's btoa() method to encode the string in Base64 format.
- Character to Binary Conversion: Convert each character in the Base64 encoded string to its binary representation using the charCodeAt() and toString(2) methods.
- Padding and Formatting: Ensure each binary representation is 8 bits long by padding with leading zeros. Combine the binary values with spaces as separators.
Example: This example shows how to convert a string to binary using Base64 encoding and conversion.
JavaScript
function stringToBinaryUsingBase64(input) {
// Encode the input string to Base64
let base64String = btoa(input);
// Convert each character of the Base64 string to its binary representation
let binaryString = Array.from(base64String).map(char => {
let binaryChar = char.charCodeAt(0).toString(2);
return binaryChar.padStart(8, '0'); // Pad with leading zeros to ensure 8 bits
}).join(' ');
return binaryString;
}
// Example usage:
let inputString = "Hello";
let binaryRepresentation = stringToBinaryUsingBase64(inputString);
console.log(binaryRepresentation);
Output01010011 01000111 01010110 01110011 01100010 01000111 00111000 00111101
Similar Reads
JavaScript Program to Convert a Number to Binary We are going to learn the conversion of a number to binary by using JavaScript, Convert a number to binary in JavaScript refers to the process of converting a decimal number into its binary representation, which uses only the digits 0 and 1 to represent the value Converting a number to binary in Jav
3 min read
JavaScript Program to Convert Decimal to Binary In this article, we are going to learn the conversion of numeric values from decimal to binary. Binary is a number system with 2 digits (0 and 1) representing all numeric values. Given a number N which is in decimal representation. our task is to convert the decimal representation of the number to i
5 min read
JavaScript Program to Add n Binary Strings In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as
3 min read
JavaScript Program to Convert Decimal to Binary Using Recursion JavaScript allows us to convert decimal numbers to their binary equivalents using recursion, offering two distinct approaches. Through recursive division and concatenation, the first method constructs the binary representation directly. The second method leverages a string and recursion, providing a
2 min read
JavaScript Program to Generate all Binary Strings From Given Pattern In this article, we are going to learn about Generating all binary strings from a given pattern in JavaScript. Generating all binary strings from a given pattern involves creating a set of binary sequences that follow the pattern's structure, where specific positions in the sequences can be filled w
3 min read
JavaScript Program to Check if all Bits can be made Same by Single Flip In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach.Examples:Input: 1101Output: YesExplanati
5 min read
Java Program to Convert Boolean to String In Java programming, you might come across the need to convert a simple "true" or "false" boolean value into a String. It may seem like a challenging task, but fear not! In this article, You will explore some methods to convert a boolean value to a string in Java Method for Boolean to String Convers
4 min read
Java Program to Convert Octal to Binary Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011Oc
5 min read
Java Program to Convert Binary to Octal A Binary (base 2) number is given, and our task is to convert it into an Octal (base 8) number. There are different ways to convert binary to decimal, which we will discuss in this article.Example of Binary to Octal Conversion:Input : 100100Output: 44Input : 1100001Output : 141A Binary Number System
5 min read
Java Program to Convert Hex String to Byte Array Hex String - A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: "245FC" is a hexadecimal string. Byte Array - A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte
4 min read