You are currently viewing 3 Easy Methods to Convert String to Byte Array in JavaScript

3 Easy Methods to Convert String to Byte Array in JavaScript

JavaScript String to ByteArray

In this we will see about how to convert a JavaScript string to a bytearray.

What is byte array?

It is a contiguous block of memory that contains a sequence of bytes. Each byte in the array represents a numeric value between 0 and 255. Byte arrays are commonly used for low-level data manipulation and network communication.

In JavaScript, byte arrays can be represented using the Uint8Array object. This object provides a view of an underlying ArrayBuffer object, which represents a fixed-length, contiguous block of memory.

Why should we convert string to byte array?

Converting a string to a byte array has several advantages,, there are:

  • Data transmission: When you send data over a network or between processes, it is often more efficient to send it as a byte array. It allows you to send it in a binary format that is easier for the receiver to parse.
  • Encryption: Many encryption algorithms operate on binary data rather than strings. It allows you to encrypt the data more easily.
  • Storage: If you need to store data in a file or database, it may be more efficient to store it as a byte array rather than a string. This is particularly true for large amounts of data, as byte arrays require less storage space than strings.
  • Compatibility: Some programming languages may only accept data in the form of byte arrays, particularly when dealing with low-level operations such as accessing memory or hardware.
READ ALSO  4 Easy Ways to string substitution in JavaScipt

How to convert a string to a byte array?

Follow these given steps to convert the string to byte array:

1. Using the TextEncoder API

// create string
const text = "I am John";

// create TextEncoder object
const encoder = new TextEncoder();

// convert string to bytearray using encode() method
const bytes = encoder.encode(text);

// printing
console.log(bytes);

// Output : [73,32,97,109,32,74,111,104,110]

In this above code:

  • We have created a variable called ‘text‘ and assigned it to ‘I am John’.
  • Then we create a new TextEncoder object by calling the constructor with no arguments to the variable ‘encoder‘.
  • Next, we use the encode method of the TextEncoder object to convert the string to a Uint8Array byte array and stored it to the ‘bytes‘ variable.
  • Finally, we log the variable ‘bytes’ to the console using console.log. Now, the variable ‘bytes’ has the byte code value of the string ‘text’.

2. Using Array.from and charCodeAt

In this method, we use the Array.from method to create a new array from each character of the string. Then we converting each character to its Unicode code point using the charCodeAt method.

//create string
const str = "Welcome";

//converting string to bytearray using Array.from and charCodeAt
const byteArray = Array.from(str, c => c.charCodeAt(0));

//Printing
console.log(byteArray);


// Output : [87,101,108,99,111,109,101]
  • In this above example code, we have created the variable ‘str‘ and assigned to the string value ‘Welcome’.
  • Then we create another variable ‘byteArray‘ for storing converted variable ‘str’ to byte array. Use the Array.from method to create a new array from each character of the string. Then we provide a callback function to Array.from that converts each character to its Unicode code point using the charCodeAt method.
  • Finally, we log the resulting byte array variable ‘byteArray‘ to the console using console.log.
READ ALSO  Difference Between let and var and const in JavaScript.

3. Using the Buffer constructor (for Node.js only)

In this method only works of Node.js only, so if you want to use this you should install the node.js.

//Create buffer constructor with pass string
const buffer = Buffer.from("Hello, world!");

//log the string
console.log(buffer);

// Output: <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21>
  • Here, we have created the variable ‘buffer‘ and just call the Buffer.from() method with a passing string as an argument.
  • Then we log the variable ‘buffer’, and see the output the byte array of string is displayed successfully.

Conclusion

Byte arrays are a powerful tool for low-level data manipulation and network communication in JavaScript. By understanding how to convert strings to byte arrays, you can unlock a wide range of possibilities in your web development projects

Leave a Reply