Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hexadecimal string of data to an ArrayBuffer in JavaScript

How do I convert the string 'AA5504B10000B5' to an ArrayBuffer?

like image 344
lidong1665 Avatar asked Mar 31 '17 02:03

lidong1665


2 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
like image 151
gyre Avatar answered Nov 09 '22 18:11

gyre


Compact one-liner version:

new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer
like image 44
Jonathan Avatar answered Nov 09 '22 19:11

Jonathan