简体   繁体   English

JavaScript中如何将16进制的字符串数据转为ArrayBuffer

[英]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#mapparseInt(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.

相关问题 如何将arraybuffer转换为字符串 - how to convert arraybuffer to string Javascript:将十六进制编码的字符串转换为十六进制字节 - Javascript: Convert a hexadecimal encoded String to a hexadecimal byte 将十六进制颜色字符串转换为JavaScript中的十六进制格式 - Convert string of hexadecimal color to hexadecimal format in JavaScript 如何在Javascript中将文本转换为ArrayBuffer,如ArrayBuffer的responseType - How to convert text to ArrayBuffer like responseType of ArrayBuffer in Javascript 将二进制 ArrayBuffer/TypedArray 数据转换为十六进制字符串 - Convert Binary ArrayBuffer/TypedArray Data to Hex String 将作为字符串发送的二进制数据转换为数组缓冲区 - convert binary data sent as string to arraybuffer 如何将十六进制字符串转换为 Uint8Array 并返回 JavaScript? - How to convert a hexadecimal string to Uint8Array and back in JavaScript? 如何在javascript或jquery中将字符串从ascii转换为十六进制 - how to convert string from ascii to hexadecimal in javascript or jquery 如何在javascript中以字符串的形式将十六进制字节流转换为实际的字节流? - How to convert Hexadecimal Byte stream in the form of string to actual bytestream in javascript? 如何在 JavaScript 中将 ASCII 转换为十六进制? - how to convert ASCII to Hexadecimal in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM