JavaScript: Convert a byte array to a hex string and vice versa

Updated: March 13, 2023 By: Goodman Post a comment

This concise and straightforward article shows you how to convert a byte array into a hex string (hexadecimal string) and vice versa in modern JavaScript (ES6 and above).

Overview

What are hex strings and byte arrays?

A hex string is a string that represents binary data using hexadecimal notation. The hexadecimal notation uses 16 symbols: 0-9 and A-F. Each symbol represents 4 bits of binary data, so two symbols can represent one byte (8 bits). For example, the hex string FF represents the byte 11111111 in binary. Hex strings can have different lengths depending on how many bytes they represent. They can also be prefixed with 0x or suffixed with h to indicate that they are hexadecimal values. For example, 0x8E2 and 8E2h are equivalent to 8E2.

A byte array is an array that stores bytes of data. A byte is a unit of information that consists of 8 bits. For example, the byte array [65, 66, 67] stores the bytes 01000001, 01000010, and 01000011 in binary.

Why do we need to convert one to the other?

We may need to convert a hex string to a byte array for various reasons. One reason is to decode data that was encoded using hex encoding. Hex encoding is a way of representing binary data as text using hexadecimal notation. It is often used to make binary data more readable or compatible with different systems or protocols. For example, URLs may use hex encoding to represent special characters or spaces.

There are several use cases of conversion from a byte array to a hex string. One of them is to encode data using hex encoding for transmission or storage purposes. Hex encoding can make binary data more compact and portable than other text formats such as base64 or ASCII. For instance, cryptographic hashes are often represented as hex strings because they are shorter and easier to compare than their binary counterparts.

Enough of talking. Now, it’s time to write some code.

Turning Byte Array into Hex String

To turn a byte array into a hex string in both the browser environment and the runtime environment (Node.js), you can follow this process:

  • Use the Array.from() method to create a new array from the byte array
  • For each element in the new array, apply a callback function that takes the byte as an argument
  • Use the bitwise AND operator (&) to mask the byte with 0xFF (255 in decimal). This ensures that only the lower 8 bits of the byte are used
  • Use the toString(16) method to convert the masked byte to a hexadecimal string
  • Use the slice(-2) method to get the last two characters of the string. This pads the string with a leading zero if it is less than two characters long
  • Use the join(”) method to concatenate all the elements of the new array into a single string

Example:

// define a reusable function
const toHexString = (bytes) => {
  return Array.from(bytes, (byte) => {
    return ('0' + (byte & 0xff).toString(16)).slice(-2);
  }).join('');
};

// try it out
const byteArr1 = new Uint8Array([0x00, 0xff, 0x10, 0x20]);
const byteArr2 = new Uint8Array([
  0x00, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0,
  0xc0, 0xd0, 0xe0, 0xf0,
]);

console.log(toHexString(byteArr1));
console.log(toHexString(byteArr2));

Output:

00ff1020
script.js:13 00ff102030405060708090a0b0c0d0e0f0

Converting Hex String into Byte Array

The steps to get the job done in both the browser environment and Node.js environment:

  • Declare an empty array to store the bytes
  • Use a loop to iterate through every pair of hex digits in the hex string
  • Use the substr(c, 2) method to get two characters from position c in the hex string
  • Use the parseInt(16) method to convert them from hexadecimal to decimal
  • Push them into the bytes array using the push() method

Example:

// Convert a hex string to a byte array
const hexToBytes = (hex) => {
  var bytes = [];

  for (var c = 0; c < hex.length; c += 2) {
    bytes.push(parseInt(hex.substr(c, 2), 16));
  }

  return bytes;
};

// try it out
const hex1 = "48656c6c6f";
const hex2 = "4d7974657874";

console.log(hexToBytes(hex1));
console.log(hexToBytes(hex2));

Output:

[72, 101, 108, 108, 111]
[77, 121, 116, 101, 120, 116]

Conclusion

You’ve learned how to turn a byte array into a hex string and vice versa in modern JavaScript. You will find this knowledge useful when working with files and transmitting information on the internet.

If you find errors or anachronisms in the code examples, please let us know by leaving comments. We will review and update them as soon as possible.