Encode Uint8Array bytes as base64 or hex
Convert Uint8Array bytes to base64, base64url or hex and decode them with the matching native methods.
You have bytes from a file and an API that expects a base64 string in JSON. If your runtime has the native Uint8Array encoders, you can turn those bytes into text without creating an intermediate binary string.
Encode the bytes you already have
A Uint8Array can encode the bytes in its view as base64 or hex. The matching static method takes the string and returns a new array. Run the example in a browser with these methods, such as Chrome 140 or later.
const bytes = new Uint8Array([0, 255, 16, 200])
const base64 = bytes.toBase64()
const hex = bytes.toHex()
console.log(base64, hex)
console.log(Array.from(Uint8Array.fromBase64(base64)))
console.log(Array.from(Uint8Array.fromHex(hex)))The first line prints AP8QyA== 00ff10c8. Both decoders return the same four bytes you started with, including the leading zero. If you have an ArrayBuffer from a file, pass it to the Uint8Array constructor first.
Use hex when you want to compare a few bytes by eye. Each pair of hex digits corresponds to one byte, so ff is 255. Use base64 where the receiving API expects it. The TC39 examples show the decoder options.
Match the alphabet the receiver expects
A service might ask for unpadded base64url. Supply both options when it does. base64url changes the characters for two values in the alphabet, and omitPadding removes trailing equals signs.
const bytes = new Uint8Array([251, 255])
const urlText = bytes.toBase64({
alphabet: 'base64url',
omitPadding: true,
})
console.log(bytes.toBase64(), urlText)
console.log(Array.from(
Uint8Array.fromBase64(urlText, { alphabet: 'base64url' }),
))You see +/8= -_8 followed by the decoded bytes. Pass the alphabet to the decoder too. Its default is standard base64, so decoding -_8 with that default throws a SyntaxError.
Keep the text boundary explicit
These methods operate on bytes. If the input is text such as a display name, call TextEncoder first to get UTF-8 bytes. Decode those bytes with TextDecoder when you need the display name back.
Treat parse errors as input errors. For example, Uint8Array.fromHex('abc') throws a SyntaxError because the last digit has no partner. If you support an older runtime, check for the specific method before calling it and keep your existing encoder or decoder for that path.