Uint8Array base64 and hex conversion
Uint8Array base64 and hex conversion methods make it easier to move between raw bytes and encoded strings. They simplify serialization for binary data workflows.
Overview
Uint8Array base64 and hex conversion methods make it easier to move between raw bytes and encoded strings. They simplify serialization for binary data workflows.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 140 | 140 | 133 | 18.2 | 140 | 18.2 | |
| Built-in object | ||||||
| The Uint8Array.fromHex() static method creates a new Uint8Array object from a hexadecimal string. | 140 | 140 | 133 | 18.2 | 140 | 18.2 |
| The setFromBase64() method of Uint8Array instances populates this Uint8Array object with bytes from a base64-encoded string, returning an object indicating how many bytes were read and written. | 140 | 140 | 133 | 18.2 | 140 | 18.2 |
| The setFromHex() method of Uint8Array instances populates this Uint8Array object with bytes from a hex-encoded string, returning an object indicating how many bytes were read and written. | 140 | 140 | 133 | 18.2 | 140 | 18.2 |
| The toBase64() method of Uint8Array instances returns a base64-encoded string based on the data in this Uint8Array object. | 140 | 140 | 133 | 18.2 | 140 | 18.2 |
| The toHex() method of Uint8Array instances returns a hex-encoded string based on the data in this Uint8Array object. | 140 | 140 | 133 | 18.2 | 140 | 18.2 |
Syntax
// Base64 → Uint8Array
const bytes = Uint8Array.fromBase64('SGVsbG8=');
// Uint8Array [72, 101, 108, 108, 111]
// Uint8Array → Base64
bytes.toBase64(); // 'SGVsbG8='
// Hex conversion
bytes.toHex(); // '48656c6c6f' Live demo
Check base64 helpers
Inspect whether Uint8Array base64 helpers are present in the runtime.
Encode bytes when supported
Use toBase64 and toHex if the proposal is implemented.
Compare with TextEncoder
Start from a string and convert it into bytes before encoding.
Use cases
Token and key encoding
Represent binary material as base64 or hex when logging, storing, or transmitting through text-based channels.
Binary message handling
Convert between byte arrays and encoded payloads without handwritten utility code.
Cautions
- Encoding conversions are still data transformations, so validate formats and error handling carefully.
- Keep an eye on memory usage when converting large buffers into large strings.
Accessibility
- No direct accessibility effect, but simpler binary handling can reduce bugs in media or document workflows.
- If encoded output is shown to users, label it clearly because raw base64 or hex is not self-explanatory.
Related links
Powered by web-features