Javascript ArrayBuffer to Hex

后端 未结 9 551
迷失自我
迷失自我 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:09

    Here is a sweet ES6 solution, using padStart and avoiding the quite confusing prototype-call-based solution of the accepted answer. It is actually faster as well.

    function bufferToHex (buffer) {
        return [...new Uint8Array (buffer)]
            .map (b => b.toString (16).padStart (2, "0"))
            .join ("");
    }
    

    How this works:

    1. An Array is created from a Uint8Array holding the buffer data. This is so we can modify the array to hold string values later.
    2. All the Array items are mapped to their hex codes and padded with 0 characters.
    3. The array is joined into a full string.

提交回复
热议问题