This code will show the data buffer as a hex string:

buff.toString('hex');
Answer from Seryh on Stack Overflow
🌐
Medium
medium.com › deno-the-complete-reference › deno-nuggets-buffer-to-hex-one-liner-701e4ce074a2
Deno nuggets: Buffer to hex one-liner | Tech Tonic
April 6, 2023 - Here is the complete code: const buf = new TextEncoder().encode("Hello from JS ArrayBuffer!"); const hex = Array.from(buf).map((b) => b.toString(16).padStart(2, "0")).join(""); console.log("// -- BUFFER:\n\n", buf, "\n\n// -- HEX:\n\n", hex);
Discussions

How can I convert an ArrayBuffer to a hexadecimal string (hex)?
Same as the above method, where ... is the hex string for the index's value, but we use a hack where we call the Array prototype's map() method with the buffer. This is a more functional approach, but if you really want speed you will always use for loops rather than ES6 array methods, as all modern JS engines optimize ... More on stackoverflow.com
🌐 stackoverflow.com
node.js - JavaScript Convert Buffer to Hex - Stack Overflow
I have a buffer in this format: And I need to convert it to hex format: More on stackoverflow.com
🌐 stackoverflow.com
March 11, 2018
node.js - Converting a buffer to a hex string - Stack Overflow
I want to convert a node JS buffer to a hex string. Obviously, I googled this first, but none of the proposed solutions work. For example, in this question a comment below the accepted answer says... More on stackoverflow.com
🌐 stackoverflow.com
How to convert Buffer array to hex? - javascript
I am getting a Buffer array back in a JSON object when I call one of my API endpoints. I would like to convert this array to a more "usable" form (hex?) so I can compare them, etc. Here is what the More on stackoverflow.com
🌐 stackoverflow.com
December 9, 2015
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.11.1 Documentation
import { Buffer } from 'node:buffer'; const buf = Buffer.from('hello world', 'utf8'); console.log(buf.toString('hex')); // Prints: 68656c6c6f20776f726c64 console.log(buf.toString('base64')); // Prints: aGVsbG8gd29ybGQ= console.log(Buffer.from('fhqwhgads', 'utf8')); // Prints: <Buffer 66 68 ...
Top answer
1 of 14
143

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
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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:

Show code snippet

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
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 14
49

Here are several methods for encoding an ArrayBuffer to hex, in order of speed. All methods were tested in Firefox initially, but afterwards I went and tested in Chrome (V8). In Chrome the methods were mostly in the same order but it did have slight differenences--the important thing is that #1 is the fastest method in all environments by a huge margin.

If you want to see how slow the currently selected answer is, you can go ahead and scroll to the bottom of this list.

TL;DR

Method #1 (just below this) is the fastest method I tested for encoding to a hex string. If, for some very good reason, you need to support IE, you may need to replace the .padStart call with the .slice trick used in method #6 when precomputing the hex octets to make sure every octet is 2 characters.

1. Precomputed Hex Octets w/ for Loop (Fastest/Baseline)

This approach computes the 2-character hex octets for every possible value of an unsigned byte: [0, 255], and then just maps each value in the ArrayBuffer through the array of octet strings. Credit to Aaron Watters for the original answer using this method.

NOTE: as mentioned by Cref, you may get a performance boost in V8 (Chromium/Chrome/Edge/Brave/etc.) by using the loop to just concatenate hex octets into one big string as you go and then returning the string after the loop. V8 seems to optimize string concatenation very well while Firefox performed better with building up an array and then .joining it into a string at the end as I did in the code below. That would probably be a micro-optimization subject to change with the whims of optimizing JS compilers though..

const byteToHex = [];

for (let n = 0; n <= 0xff; ++n)
{
    const hexOctet = n.toString(16).padStart(2, "0");
    byteToHex.push(hexOctet);
}

function hex(arrayBuffer)
{
    const buff = new Uint8Array(arrayBuffer);
    const hexOctets = []; // new Array(buff.length) is even faster (preallocates necessary array size), then use hexOctets[i] instead of .push()

    for (let i = 0; i < buff.length; ++i)
        hexOctets.push(byteToHex[buff[i]]);

    return hexOctets.join("");
}

2. Precomputed Hex Octets w/ Array.map (~30% slower)

Same as the above method, where we precompute an array in which the value for each index is the hex string for the index's value, but we use a hack where we call the Array prototype's map() method with the buffer. This is a more functional approach, but if you really want speed you will always use for loops rather than ES6 array methods, as all modern JS engines optimize them much better.

IMPORTANT: You cannot use new Uint8Array(arrayBuffer).map(...). Although Uint8Array implements the ArrayLike interface, its map method will return another Uint8Array which cannot contain strings (hex octets in our case), hence the Array prototype hack.

function hex(arrayBuffer)
{
    return Array.prototype.map.call(
        new Uint8Array(arrayBuffer),
        n => byteToHex[n]
    ).join("");
}

3. Precomputed ASCII Character Codes (~230% slower)

Well this was a disappointing experiment. I wrote up this function because I thought it would be even faster than Aaron's precomputed hex octets--boy was I wrong LOL. While Aaron maps entire bytes to their corresponding 2-character hex codes, this solution uses bitshifting to get the hex character for the first 4 bits in each byte and then the one for the last 4 and uses String.fromCharCode(). Honestly I think String.fromCharCode() must just be poorly optimized, since it is not used by very many people and is low on browser vendors' lists of priorities.

const asciiCodes = new Uint8Array(
    Array.prototype.map.call(
        "0123456789abcdef",
        char => char.charCodeAt()
    )
);

function hex(arrayBuffer)
{
    const buff = new Uint8Array(arrayBuffer);
    const charCodes = new Uint8Array(buff.length * 2);

    for (let i = 0; i < buff.length; ++i)
    {
        charCodes[i * 2] = asciiCodes[buff[i] >>> 4];
        charCodes[i * 2 + 1] = asciiCodes[buff[i] & 0xf];
    }

    return String.fromCharCode(...charCodes);
}

4. Array.prototype.map() w/ padStart() (~290% slower)

This method maps an array of bytes using the Number.toString() method to get the hex and then padding the octet with a "0" if necessary via the String.padStart() method.

IMPORTANT: String.padStart() is a relative new standard, so you should not use this or method #5 if you are planning on supporting browsers older than 2017 or so or Internet Explorer. TBH if your users are still using IE you should probably just go to their houses at this point and install Chrome/Firefox. Do us all a favor. :^D

function hex(arrayBuffer)
{
    return Array.prototype.map.call(
        new Uint8Array(arrayBuffer),
        n => n.toString(16).padStart(2, "0")
    ).join("");
}

5. Array.from().map() w/ padStart() (~370% slower)

This is the same as #4 but instead of the Array prototype hack, we create an actual number array from the Uint8Array and call map() on that directly. We pay in speed though.

function hex(arrayBuffer)
{
    return Array.from(new Uint8Array(arrayBuffer))
        .map(n => n.toString(16).padStart(2, "0"))
        .join("");
}

6. Array.prototype.map() w/ slice() (~450% slower)

This is the selected answer, do not use this unless you are a typical web developer and performance makes you uneasy (answer #1 is supported by just as many browsers).

function hex(arrayBuffer)
{
    return Array.prototype.map.call(
        new Uint8Array(arrayBuffer),
        n => ("0" + n.toString(16)).slice(-2)
    ).join("");
}

Lesson #1

Precomputing stuff can be a very effective memory-for-speed tradeoff sometimes. In theory, the array of precomputed hex octets can be stored in just 1024 bytes (256 possible hex values ⨉ 2 characters/value ⨉ 2 bytes/character for a UTF-16 string representation used by most/all browsers), which is nothing in a modern computer. Realistically there are some more bytes in there used for storing the array and string lengths and maybe type information since this is JavaScript, but the memory usage is still negligible for a massive performance improvement.

Lesson #2

Help out the optimizing compiler. The browser's JavaScript compiler regularly attempts to understand your code and break it down to the fastest possible machine code for your CPU to execute. Because JavaScript is a very dynamic language, this can be hard to do and sometimes the browser just gives up and leaves all sorts of type checks and worse under-the-hood because it can't be sure that x will indeed be a string or number, and vice versa. Using modern functional programming additions like the .map method of the built-in Array class can cause headaches for the browser because callback functions can capture outside variables and do all sorts of other things that often hurt performance. For-loops are well-studied and relatively simple constructs, so the browser developers have incorporated all sorts of tricks for the compiler to optimize your JavaScript for-loops. Keep it simple.

🌐
Webdevtutor
webdevtutor.net › blog › javascript-buffer-to-string-hex
Converting JavaScript Buffer to String Hex: A Comprehensive Guide
When dealing with large buffers, it's important to consider performance and memory usage. One common approach is to convert the buffer to a hex string in chunks to avoid memory issues. Here's an example of converting a large buffer to a hex string in chunks:
🌐
Webdevtutor
webdevtutor.net › blog › javascript-buffer-to-hex
Converting JavaScript Buffer to Hex: A Comprehensive Guide
This will output the hexadecimal representation of the first 5 bytes of the binary data. Converting JavaScript buffer to hex is a common operation when working with binary data.
Find elsewhere
🌐
Readthedocs
node.readthedocs.io › en › latest › api › buffer
Buffer - node - Read the Docs
That is, new Uint32Array(new Buffer([1,2,3,4])) creates a 4-element Uint32Array with elements [1,2,3,4], not a Uint32Array with a single element [0x1020304] or [0x4030201]. NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer instead of cloning it.
🌐
W3Resource
w3resource.com › node.js › nodejs-buffer.php
Using Buffers in Node.js - w3resource<
November 13, 2023 - Here is an example : The buffer size of str1 was 10 and length of the specified string is 7, therefore, the last three values within the array shows 0. The buf[index] is used to get and set the octet at index.
🌐
The Code Barbarian
thecodebarbarian.com › an-overview-of-buffers-in-node-js
An Overview of Buffers in Node.js | www.thecodebarbarian.com
The toString() function takes an encoding parameter that tells Node.js how you want to interpret your buffer. For example, below is how you print the above buffer in hexadecimal: buf.toString('hex'); // "48656c6c6f2c20576f726c64" Node.js supports ...
🌐
GitHub
github.com › LinusU › array-buffer-to-hex
GitHub - LinusU/array-buffer-to-hex: Turn an `ArrayBuffer` into a string of hexadecimal characters · GitHub
Turn an ArrayBuffer into a string of hexadecimal characters. ... const arrayBufferToHex = require('array-buffer-to-hex') const randomData = crypto.getRandomValues(new Uint8Array(16)).buffer const string = arrayBufferToHex(randomData) console.log(string) //=> "a2c57b9bc22056336ce5a3ec917819e0"
Author: LinusU
🌐
GitHub
github.com › nodejs › node › issues › 24491
Buffer.from for the hex string · Issue #24491 · nodejs/node
November 19, 2018 - Version: v10.13.0 Platform: Linux dcloud_dev 3.13.0-88-generic #135-Ubuntu SMP Wed Jun 8 21:10:42 UTC 2016 x86_64 GNU/Linux Subsystem: I use the conversion to the hexadecimal number buffer as follows Buffer.from(number.toString(16), 'hex...
🌐
npm
npmjs.com › package › array-buffer-to-hex
array-buffer-to-hex - npm
October 19, 2017 - Returns a new string with the hexadecimal content from the array buffer.
      » npm install array-buffer-to-hex
    
Published: Oct 19, 2017
Version: 1.0.0
🌐
Mastering JS
masteringjs.io › tutorials › node › buffer-to-string
Using the Buffer `toString()` Function in Node.js - Mastering JS
August 21, 2020 - const fs = require('fs'); const buf = fs.readFileSync('./package.json'); buf.toString('hex'); // '7b0a2020...' Which encoding is correct depends on your use case and the data stored in the buffer.
🌐
Medium
medium.com › @ryan_forrester_ › buffer-to-string-in-javascript-how-to-guide-b24027575419
Buffer to String in JavaScript (How To Guide) | by ryan | Medium
January 7, 2025 - The buffer is then converted to a hexadecimal string using the toString method with 'hex' encoding.
🌐
npm
npmjs.com › package › hex-to-array-buffer
hex-to-array-buffer - npm
import hexToArrayBuffer from 'hex-to-array-buffer' const buffer = hexToArrayBuffer('ceae96a325e1dc5dd4f405d905049ceb') console.log(buffer) //=> ArrayBuffer { byteLength: 16 }
      » npm install hex-to-array-buffer
    
🌐
Medium
medium.com › @techsuneel99 › how-to-convert-a-buffer-to-json-in-node-js-4fa9ef98160
How to convert a Buffer to JSON in Node.js ? | by Suneel Kumar | Medium
December 31, 2023 - To get hex string representation of the Buffer: // Creating a Buffer with some binary data const binaryData = Buffer.from('Hello, Hex Encoding!', 'utf-8'); // Getting the hex string representation of the Buffer const hexString = binaryData....