Convert a Uint8Array

Uint8Array is the workhorse binary type in Ende: file reads, network payloads, and hashes all produce or consume it. This example shows how to convert one into the other common binary and text representations.

Edit on GitHub

We start with a Uint8Array containing the bytes of the string "Hello".

const bytes = new TextEncoder().encode("Hello");

To convert to a string, decode the bytes with TextDecoder.

const text = new TextDecoder().decode(bytes);
console.log(text); // Hello

A Uint8Array is a view over an underlying ArrayBuffer. The view may cover only part of that buffer, so to get an exact ArrayBuffer, slice the range described by byteOffset and byteLength.

const exact = bytes.buffer.slice(
  bytes.byteOffset,
  bytes.byteOffset + bytes.byteLength
);

console.log(exact.byteLength); // 5

If the view is known to span its whole buffer, the buffer property can be used directly. This does not copy the bytes.

console.log(bytes.buffer.byteLength); // 5

To convert to a Blob, pass the array in the parts list of the Blob constructor.

const blob = new Blob([bytes]);
console.log(blob.size); // 5

To create a DataView over the same bytes, pass the buffer together with the offset and length of the view.

const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
console.log(view.getUint8(4)); // 111

ReadableStream.from wraps any iterable into a stream. This is useful for APIs that consume streams, like the Response constructor.

const stream = ReadableStream.from([bytes]);
console.log(stream instanceof ReadableStream); // true

To convert to a base64 or hex string, use the built-in methods available . The matching fromBase64 and fromHex methods decode back.

console.log(bytes.toBase64()); // SGVsbG8=
console.log(bytes.toHex()); // 48656c6c6f
const decoded = Uint8Array.fromBase64("SGVsbG8=");
console.log(decoded); // Uint8Array(5) [ 72, 101, 108, 108, 111 ]

Run this example locally using the Ende CLI:

ende run https://docs.ende.sh/examples/scripts/convert_uint8array.ts

Additional resources