Byte array to Hex string conversion in javascript

前端 未结 7 801
礼貌的吻别
礼貌的吻别 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:01

    When converting a byte array to a hex array, we have to consider how they can be signed numbers. If so, we gotta convert them to decimal numbers first. signed numbers to decimal conversion. Then, we can use the .toString(16) method to convert it to hex.

    const hexArr = byteArr.map((byte) => {
        if (byte < 0) {
          byte = -((byte ^ 0xff) + 1); //converting 2s complement to a decimal number
        }
        //add padding at the start to ensure it's always 2 characters long otherwise '01' will be '1'
        return byte.toString(16).padStart(2, '0'); 
    });
    

提交回复
热议问题