Javascript ArrayBuffer to Hex

后端 未结 9 541
迷失自我
迷失自我 2020-11-30 05:51

I\'ve got a Javascript ArrayBuffer that I would like to be converted into a hex string.

Anyone knows of a function that I can call or a pre written function already

9条回答
  •  一整个雨季
    2020-11-30 06:25

    This one's inspired by Sam Claus' #1 which is indeed the fastest method on here. Still, I've found that using plain string concatenation instead of using an array as a string buffer is even faster! At least it is on Chrome. (which is V8 which is almost every browser these days and NodeJS)

    const len = 0x100, byteToHex = new Array(len), char = String.fromCharCode;
    let n = 0;
    for (; n < 0x0a; ++n) byteToHex[n] = '0' + n;
    for (; n < 0x10; ++n) byteToHex[n] = '0' + char(n + 87);
    for (; n < len; ++n) byteToHex[n] = n.toString(16);
    function byteArrayToHex(byteArray) {
        const l = byteArray.length;
        let hex = '';
        for (let i = 0; i < l; ++i) hex += byteToHex[byteArray[i] % len];
        return hex;
    }
    function bufferToHex(arrayBuffer) {
        return byteArrayToHex(new Uint8Array(arrayBuffer));
    }
    

提交回复
热议问题