Ethereum: Byte array to hexadecimal and back again in JavaScript [closed]

Convert a matrix of bytes to hexadecimal and back in JavaScript

In this article, we will explore how to take a matrix of bytes generated using the web cryptographic API and convert it again into a hexadecimal format.

Generation of a random bytes matrix

===============================

We begin generating a random bytes matrix of 16 elements using Window.crypto.getrandomvalues ​​(New Uint8array (16)). This method uses the random numbers generator of the browser to fill the Uint8array with random values.

`JavaScript

var mybyterary = window.crypto.getrandomvalues ​​(New Uint8array (16));

Convert the Matrix of Bytes to Hexadecimal

--------------------------------------

To convert a matrix of bytes into hexadecimal, we can use thetostring () method with the radix parameter established in 16 (hexadecimal). We will also need to specify the type of number to be used when representing each byte value. This is how you can do it:

`JavaScript

Mybyteraray.Foreach (Function (byte) {

var hex = byte.tostring (16) .padstart (2, '0');

console.log (hex);

});

In this example, we are hearing about each element in theMybyteraryand turning its binary representation into a hexadecimal chain. We usePadstart (2, ‘0’)To ensure that each hexadecimal value has exactly 2 characters.

Convert hexadecimal back to the bytes matrix

Ethereum: Byte array to hexadecimal and back again in JavaScript [closed]

----------------------------------------

To convert a hexadecimal chain again into a matrix of bytes, we can use theParseint ()based 16 method and then create a new Uint8array. We will also have to fill in the resulting values ​​with zeros if necessary.

JavaScript

Var Hexstring = '18114316136';

var bytearray = new uint8array (hexstring.length);

for (var i = 0; i

Value var = paseint (hexstring [i], 16);

if ((value and 0x80)! == 0) {

// Take the 8 bits to the next position

bytearray [i] = 0xff | value and 0x7f;

} others {

// Do not carry; Simply add the Byte value

bytearray [i] = value;

}

}

Console.log (bytearray);

In this example, we are turning a hexadecimal chain to a Uint8array. We useParseint ()` with base 16 and then verify the hauls (that is, values ​​greater than or equal to 128). If there is a transport, we establish the corresponding byte value in the ‘bytearray’. Otherwise, we simply add the original value.

Example of use cases

———————

Here are some cases of example use for this code:

  • Turning random numbers generated by a web cryptographic API (for example, crypto.Getrandomvalues ​​()) to hexadecimal and returns to a Uint8array.

  • Use of the resulting bytes matrix as an entrance for a cryptographic algorithm or data processing task.

Following these steps, it can convert efficiently between a matrix of bytes and hexadecimal format in Javascript using the web crypto API.

Artigos relacionados

Deixe o primeiro comentário