簡體   English   中英

JavaScript中如何將16進制的字符串數據轉為ArrayBuffer

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

如何將字符串'AA5504B10000B5'轉換為ArrayBuffer

您可以將正則表達式與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 

緊湊的單線版本:

new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer

當十六進制字符串為空時,接受的答案會引發異常。 這是一個更安全的解決方案:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM