Byte array to Hex string conversion in javascript

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

    Since this is the first Google hit for "js byte to hex" and I needed some time to understand the function of Bergi, I rewrote the function and added some comments that made it easier for me to understand:

    function byteToHex(byte) {
      // convert the possibly signed byte (-128 to 127) to an unsigned byte (0 to 255).
      // if you know, that you only deal with unsigned bytes (Uint8Array), you can omit this line
      const unsignedByte = byte & 0xff;
    
      // If the number can be represented with only 4 bits (0-15), 
      // the hexadecimal representation of this number is only one char (0-9, a-f). 
      if (unsignedByte < 16) {
        return '0' + unsignedByte.toString(16);
      } else {
        return unsignedByte.toString(16);
      }
    }
    
    // bytes is an typed array (Int8Array or Uint8Array)
    function toHexString(bytes) {
      // Since the .map() method is not available for typed arrays, 
      // we will convert the typed array to an array using Array.from().
      return Array.from(bytes)
        .map(byte => byteToHex(byte))
        .join('');
    }
    
    • For more information about the const unsignedByte = byte & 0xff-part, check What does AND 0xFF do?.
    • Array.from is not available in every browser (e.g. not in IE11), check How to convert a JavaScript Typed Array into a JavaScript Array for more information

    The OP forgot to add the leading 0 for numbers that can be displayed with only 4 bits.

提交回复
热议问题