Converting a Byte Array to Hexadecimal and Back in JavaScript
In this article, we will explore how to take a byte array generated using the Web Crypto API and convert it back to hexadecimal format.
Generating a Random Byte Array
===============================================
We will start by generating a random byte array of 16 elements using window.crypto.getRandomValues(new Uint8Array(16)). This method uses the browser’s random number generator to fill the Uint8Array with random values.
var myByteArray = window.crypto.getRandomValues(new Uint8Array(16));
Converting a Byte Array to Hexadecimal
————————————
To convert a byte array to hexadecimal, we can use the toString() method with the radix parameter set to 16 (hexadecimal). We will also need to specify the type of number to use to represent each byte value. You can do this like this:
myByteArray.forEach(function(byte) {
var hex = byte.toString(16).padStart(2, '0');
console.log(hex);
});
In this example, we iterate over each element in the myByteArray array and convert its binary representation to a hexadecimal string. We use padStart(2, '0') to ensure that each hexadecimal value has exactly 2 characters.
Converting a hexadecimal number back to a byte array
—————————————–
To convert a hexadecimal string back to a byte array, we can use the parseInt() method with base 16 and then create a new Uint8Array array. We will need to pad the resulting values with zeros if necessary.
var hexString = '18114316136';
var byteArray = new Uint8Array(hexString.length);
for (var i = 0; i < hexString.length; i++) {
var value = parseInt(hexString[i], 16);
if ((value & 0x80) !== 0) {
// Carry 8 bits to next position
byteArray[i] = 0xFF | value & 0x7F;
} else {
// Don't carry; just append the byte value
byteArray[i] = value;
}
}
console.log(byteArray);
In this example, we convert a hexadecimal string to a Uint8Array. We use parseInt() with base 16 and then check for any carry (i.e. values greater than or equal to 128). If there is a transfer, we set the corresponding byte value in the byteArray array. Otherwise, we simply append the original value.
Usage Examples
![Ethereum: Byte array to hexadecimal and back again in JavaScript [closed]](https://en.ppottina.com/wp-content/uploads/2025/02/dcbb5209.png)
————————-
Here are some examples of how this code can be used:
- Convert random numbers generated by the Web Crypto API (e.g. crypto.getRandomValues()) to hexadecimal and back to a Uint8Array array.
- Use the resulting byte array as input to a cryptographic algorithm or data processing task.
By following these steps, you can efficiently convert between a byte array and hexadecimal format in JavaScript using the Web Crypto API.