Javascript ArrayBuffer to Hex

后端 未结 9 549
迷失自我
迷失自我 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条回答
  •  萌比男神i
    2020-11-30 06:13

    The following solution uses precomputed lookup tables for both forward and backward conversion.

    // look up tables
    var to_hex_array = [];
    var to_byte_map = {};
    for (var ord=0; ord<=0xff; ord++) {
        var s = ord.toString(16);
        if (s.length < 2) {
            s = "0" + s;
        }
        to_hex_array.push(s);
        to_byte_map[s] = ord;
    }
    
    // converter using lookups
    function bufferToHex2(buffer) {
        var hex_array = [];
        //(new Uint8Array(buffer)).forEach((v) => { hex_array.push(to_hex_array[v]) });
        for (var i=0; i

    This solution is faster than the winner of the previous benchmark: http://jsben.ch/owCk5 tested in both Chrome and Firefox on a Mac laptop. Also see the benchmark code for a test validation function.

    [edit: I change the forEach to a for loop and now it's even faster.]

提交回复
热议问题