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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read