Byte array to Hex string conversion in javascript

前端 未结 7 753
礼貌的吻别
礼貌的吻别 2020-12-30 21:30

I have a byte array of the form [4,-101,122,-41,-30,23,-28,3,..] which I want to convert in the form 6d69f597b217fa333246c2c8 I\'m using below func

7条回答
  •  迷失自我
    2020-12-30 22:18

    All of the previous solutions work but they all require the creation of many strings and concatenation and slicing of the created strings. I got thinking there has to be a better way to go about it now that there are typed arrays. I originally did this using node and then commented out the lines that use Buffer and changed them to TypedArrays so it would work in a browser too.

    It's more code but it's significantly faster, at least in the quick jsperf I put together. The string manipulation version in the accepted answer performed 37000 ops/sec while the code below managed 317000 ops/sec. There is a lot of hidden overhead in creating string objects.

    function toHexString (byteArray) {
      //const chars = new Buffer(byteArray.length * 2);
      const chars = new Uint8Array(byteArray.length * 2);
      const alpha = 'a'.charCodeAt(0) - 10;
      const digit = '0'.charCodeAt(0);
    
      let p = 0;
      for (let i = 0; i < byteArray.length; i++) {
          let nibble = byteArray[i] >>> 4;
          chars[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
          nibble = byteArray[i] & 0xF;
          chars[p++] = nibble > 9 ? nibble + alpha : nibble + digit;    
      }
    
      //return chars.toString('utf8');
      return String.fromCharCode.apply(null, chars);
    }
    

提交回复
热议问题