Files and data

Convert a byte array to a hexadecimal string

Convert each byte to base 16 and pad it to two characters to obtain a readable hexadecimal representation. Padding preserves byte boundaries for small values.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const bytes = new Uint8Array([0, 15, 16, 255]);
const hex = [...bytes].map(byte => byte.toString(16).padStart(2, "0")).join("");
console.log(hex);

How it works

A byte spans hexadecimal 00 through ff. Without padding, a value such as 15 would produce f and become ambiguous when concatenated. Hex output is useful for showing a digest or a small binary fixture without interpreting it as text.

Limits and mistakes

Hex doubles the number of characters compared with the byte count and is not compression or encryption. For large files, avoid converting the entire input merely to inspect a header. A reverse parser must validate even length and valid hex digits.

Check the result

Expect 000f10ff. Check leading zero bytes and values below 16, which are the easiest cases to misrepresent without padding.

Sources

Reference documentation for the behavior used in this guide: