
Native Binary Encoding with Uint8Array toBase64 and toHex
For more than a decade, encoding raw binary bytes into Base64 or hexadecimal strings in browser JavaScript required awkward workarounds. Developers had to iterate byte-by-byte to build an intermediate ASCII string for btoa, split large buffers into chunks to avoid call-stack limits with String.fromCharCode, or allocate arrays of two-character strings and join them for hex output. Those patterns created unnecessary garbage-collection pressure, doubled memory usage during serialization, and introduced subtle UTF-16 encoding bugs whenever binary data met text-oriented APIs.
The TC39 Uint8Array Base64 and Hex specification—now natively supported across modern JavaScript runtimes in 2026—eliminates those detours by placing binary-to-text encoding directly on typed arrays. Methods like toBase64(), toHex(), Uint8Array.fromBase64(), and Uint8Array.fromHex() run in native engine code without intermediate JS strings, while setFromBase64() and setFromHex() decode straight into preallocated buffers for zero-allocation streaming pipelines. Built-in support for base64url alphabets, optional padding omission, and strict chunk validation also prevents the malformed-input edge cases that plagued custom decoders.
Example
// Encode binary bytes to Base64, URL-safe Base64, and Hex natively
const digest = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xfb, 0xff]);
const standardB64 = digest.toBase64();
// "SGVsbG/7/w=="
const urlSafeB64 = digest.toBase64({
alphabet: 'base64url',
omitPadding: true
});
// "SGVsbG_7_w"
const hexString = digest.toHex();
// "48656c6c6ffbff"
// Decode back into Uint8Array with strict validation
const restoredFromB64 = Uint8Array.fromBase64(urlSafeB64, {
alphabet: 'base64url',
lastChunkHandling: 'strict'
});
const restoredFromHex = Uint8Array.fromHex(hexString);
Implementation
/**
* BinaryEncodingCodec
* Production utility providing native Uint8Array Base64/Hex conversion
* with automatic chunked fallbacks for legacy environments.
*/
export const BinaryEncodingCodec = (() => {
const hasNativeBase64 =
typeof Uint8Array.prototype.toBase64 === 'function' &&
typeof Uint8Array.fromBase64 === 'function';
const hasNativeHex =
typeof Uint8Array.prototype.toHex === 'function' &&
typeof Uint8Array.fromHex === 'function';
const HEX_LUT = Array.from({ length: 256 }, (_, i) =>
i.toString(16).padStart(2, '0')
);
/**
* Encode a Uint8Array into standard or URL-safe Base64.
* @param {Uint8Array} bytes
* @param { { urlSafe?: boolean, omitPadding?: boolean } } [options]
* @returns {string}
*/
function encodeBase64(bytes, { urlSafe = false, omitPadding = false } = {}) {
if (!(bytes instanceof Uint8Array)) {
throw new TypeError('Expected a Uint8Array instance.');
}
if (hasNativeBase64) {
return bytes.toBase64({
alphabet: urlSafe ? 'base64url' : 'base64',
omitPadding
});
}
// Chunked fallback avoids Maximum Call Stack Size Exceeded on large buffers
const CHUNK_SIZE = 0x8000;
const parts = [];
for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
parts.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK_SIZE)));
}
let encoded = btoa(parts.join(''));
if (urlSafe) {
encoded = encoded.replace(/\+/g, '-').replace(/\//g, '_');
}
if (omitPadding) {
encoded = encoded.replace(/=+$/, '');
}
return encoded;
}
/**
* Decode a Base64 or Base64URL string into a Uint8Array.
* @param {string} input
* @param { { urlSafe?: boolean, strict?: boolean } } [options]
* @returns {Uint8Array}
*/
function decodeBase64(input, { urlSafe = false, strict = true } = {}) {
if (typeof input !== 'string') {
throw new TypeError('Expected a Base64 string.');
}
if (hasNativeBase64) {
return Uint8Array.fromBase64(input, {
alphabet: urlSafe ? 'base64url' : 'base64',
lastChunkHandling: strict ? 'strict' : 'loose'
});
}
const normalized = urlSafe
? input.replace(/-/g, '+').replace(/_/g, '/')
: input;
const padded = normalized.padEnd(
normalized.length + ((4 - (normalized.length % 4)) % 4),
'='
);
const binary = atob(padded);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
out[i] = binary.charCodeAt(i);
}
return out;
}
/**
* Encode a Uint8Array into a lowercase hexadecimal string.
* @param {Uint8Array} bytes
* @returns {string}
*/
function encodeHex(bytes) {
if (!(bytes instanceof Uint8Array)) {
throw new TypeError('Expected a Uint8Array instance.');
}
if (hasNativeHex) {
return bytes.toHex();
}
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += HEX_LUT[bytes[i]];
}
return hex;
}
/**
* Decode a hexadecimal string into a Uint8Array.
* @param {string} hex
* @returns {Uint8Array}
*/
function decodeHex(hex) {
if (typeof hex !== 'string' || hex.length % 2 !== 0) {
throw new SyntaxError('Hex string must have an even length.');
}
if (hasNativeHex) {
return Uint8Array.fromHex(hex);
}
if (!/^[0-9a-fA-F]*$/.test(hex)) {
throw new SyntaxError('Invalid hexadecimal character detected.');
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
/**
* Decode Base64 directly into a preallocated buffer for streaming workloads.
* @param {string} chunk
* @param {Uint8Array} target
* @returns { { read: number, written: number } }
*/
function decodeIntoBuffer(chunk, target) {
if (typeof target.setFromBase64 === 'function') {
return target.setFromBase64(chunk, { lastChunkHandling: 'stop-before-partial' });
}
const decoded = decodeBase64(chunk, { strict: false });
const count = Math.min(decoded.length, target.length);
target.set(decoded.subarray(0, count));
return { read: chunk.length, written: count };
}
return {
encodeBase64,
decodeBase64,
encodeHex,
decodeHex,
decodeIntoBuffer
};
})();
Main Point: Native Uint8Array Base64 and Hex methods eliminate slow string-building loops and call-stack workarounds while offering strict decoding and zero-allocation buffer writes.
Credits
Photo by Willian Justen de Vasconcellos on Unsplash