[英]How to convert a hexadecimal string of data to an ArrayBuffer in JavaScript
How do I convert the string 'AA5504B10000B5'
to an ArrayBuffer
?如何将字符串
'AA5504B10000B5'
转换为ArrayBuffer
?
You could use regular expressions together with Array#map
and parseInt(string, radix)
: 您可以将正则表达式与
Array#map
和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
Compact one-liner version:紧凑的单线版本:
new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer
The accepted answer throws an exception when the hex string is empty.当十六进制字符串为空时,接受的答案会引发异常。 Here is a safer solution:
这是一个更安全的解决方案:
function hex_decode(string) {
let bytes = [];
string.replace(/../g, function (pair) {
bytes.push(parseInt(pair, 16));
});
return new Uint8Array(bytes).buffer;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.