I want to convert a hexadecimal string like bada55
into a Uint8Array
and back again.
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).
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.
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.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With