Byte array to Hex string conversion in javascript

前端 未结 7 798
礼貌的吻别
礼貌的吻别 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 21:55

    A more concise and performant (see https://jsperf.com/byte-array-to-hex-string) alternative using Array.reduce():

    function toHexString(byteArray) {
      return byteArray.reduce((output, elem) => 
        (output + ('0' + elem.toString(16)).slice(-2)),
        '');
    }
    

    (Also without "& 0xFF" because in my opinion if an array is passed in that contains values larger than 255, the output should be messed up, so that the user can more easily see that their input was wrong.)

提交回复
热议问题