javascripthexarraybuffer

How can I convert an ArrayBuffer to a hexadecimal string (hex)?


I've got a JavaScript ArrayBuffer that I would like to be converted into a hex string.

Is there a function that I can call or a pre-written function already out there?

I have only been able to find ArrayBuffer to string functions, but I want the hexdump of the array buffer instead.


Solution

  • function buf2hex(buffer) { // buffer is an ArrayBuffer
      return [...new Uint8Array(buffer)]
          .map(x => x.toString(16).padStart(2, '0'))
          .join('');
    }
    
    // EXAMPLE:
    const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer;
    console.log(buf2hex(buffer)); // = 04080c10

    This function works in four steps:

    1. Converts the buffer into an array.
    2. For each x the array, it converts that element to a hex string (e.g., 12 becomes c).
    3. Then it takes that hex string and left pads it with zeros (e.g., c becomes 0c).
    4. Finally, it takes all of the hex values and joins them into a single string.

    Below is another longer implementation that is a little easier to understand, but essentially does the same thing:

    function buf2hex(buffer) { // buffer is an ArrayBuffer
      // create a byte array (Uint8Array) that we can use to read the array buffer
      const byteArray = new Uint8Array(buffer);
      
      // for each element, we want to get its two-digit hexadecimal representation
      const hexParts = [];
      for(let i = 0; i < byteArray.length; i++) {
        // convert value to hexadecimal
        const hex = byteArray[i].toString(16);
        
        // pad with zeros to length 2
        const paddedHex = ('00' + hex).slice(-2);
        
        // push to array
        hexParts.push(paddedHex);
      }
      
      // join all the hex values of the elements into a single string
      return hexParts.join('');
    }
    
    // EXAMPLE:
    const buffer = new Uint8Array([ 4, 8, 12, 16 ]).buffer;
    console.log(buf2hex(buffer)); // = 04080c10