Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hexadecimal string to Uint8Array and back in JavaScript?

I want to convert a hexadecimal string like bada55 into a Uint8Array and back again.

like image 382
David Braun Avatar asked Aug 17 '16 03:08

David Braun


People also ask

What is Uint8Array in JavaScript?

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

How do you use hexadecimal in JavaScript?

Uses of Hexadecimal Numbers in JavaScriptJavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.

Can we convert string to hex?

parseInt(hex, 16) to convert the String to Hex and vice versa. The idea is convert String <==> Decimal <==> Hex , for example char a , decimal is 97, hex is 61.

How do you convert a byte array to a hexadecimal string?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .


1 Answers

Vanilla JS:

const fromHexString = hexString =>   new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));  const toHexString = bytes =>   bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');  console.log(toHexString(new Uint8Array([0, 1, 2, 42, 100, 101, 102, 255]))) console.log(fromHexString('0001022a646566ff')) 

Note: this method trusts its input. If the provided input has a length of 0, an error will be thrown. If the length of the hex-encoded buffer is not divisible by 2, the final byte will be parsed as if it were prepended with a 0 (e.g. aaa is interpreted as aa0a).

If the hex is potentially malformed or empty (e.g. user input), check its length and handle the error before calling this method, e.g.:

const missingLetter = 'abc'; if(missingLetter.length === 0 || missingLetter.length % 2 !== 0){   throw new Error(`The string "${missingLetter}" is not valid hex.`) } fromHexString(missingLetter); 

Source: the Libauth library (hexToBin method)

like image 140
Jason Dreyzehner Avatar answered Oct 09 '22 21:10

Jason Dreyzehner