How do I convert the string 'AA5504B10000B5' to an ArrayBuffer?
4 Answers
You could use regular expressions together with Array#map and parseInt(string, radix):
var hex = 'AA5504B10000B5'
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}))
console.log(typedArray)
console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])
var buffer = typedArray.buffer
Comments
If you don't want to use RegEx, here's a solution that is over x2 more performant than the accepted answer. Benchmark: https://jsbm.dev/DTjrcliqrjhHu
const decodeHex = (string) => {
const uint8array = new Uint8Array(Math.ceil(string.length / 2));
for (let i = 0; i < string.length;)
uint8array[i / 2] = Number.parseInt(string.slice(i, i += 2), 16);
return uint8array;
}
const result = decodeHex("AA5504B10000B5");
console.log(result.constructor.name, result);
2 Comments
suluke
There is still plenty more performance to be had it seems. I added some additional approaches in this jsbenchmark: jsbm.dev/qWUyMCEYHlUf0. I find it a lot of fun :)
Function
single-expression variant (might be slower due to
.map): const decodeHex = hex => new Uint8Array(Array.from({ length: Math.ceil(hex.length / 2) }).map((_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)))