DEV Community

楊東霖
楊東霖

Posted on • Originally published at devtoolkit.cc

Base64 vs Hex Encoding: Which Should You Use and When?

When you need to represent binary data as printable text, two encodings dominate the landscape: base64 and hex. Understanding base64 vs hex encoding is not just academic — choosing the wrong one can bloat your payloads, break your URLs, or make cryptographic output harder to work with downstream. This guide explains exactly how each encoding works, quantifies the size trade-offs, and maps out the real-world scenarios where each one shines.

How Hex Encoding Works

Hex encoding (also called Base16) converts every byte into exactly two hexadecimal characters from the alphabet 0–9 and a–f. Since a byte holds 8 bits and a hex digit holds 4 bits, the math is simple: one byte always becomes two characters.

// Node.js
const buf = Buffer.from('Hi');
console.log(buf.toString('hex')); // '4869'

// Browser
function toHex(str) {
  return Array.from(new TextEncoder().encode(str))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}
console.log(toHex('Hi')); // '4869'
Enter fullscreen mode Exit fullscreen mode

The resulting string is 100% ASCII — every character is either a digit or a lowercase letter a–f (or uppercase, depending on the library). This makes hex trivially safe for display, logging, and copy-paste workflows.

How Base64 Encoding Works

Base64 takes every 3 bytes of input (24 bits) and encodes them as 4 characters drawn from a 64-character alphabet: A–Z, a–z, 0–9, +, and /. If the input isn't a multiple of 3 bytes, padding characters (=) are appended.

// Node.js
const buf = Buffer.from('Hello, World!');
console.log(buf.toString('base64')); // 'SGVsbG8sIFdvcmxkIQ=='

// Browser
console.log(btoa('Hello, World!')); // 'SGVsbG8sIFdvcmxkIQ=='

// Decode
console.log(atob('SGVsbG8sIFdvcmxkIQ==')); // 'Hello, World!'
Enter fullscreen mode Exit fullscreen mode

Size Comparison: The Numbers That Matter

Both encodings increase size relative to raw binary, but by different amounts:

  • Hex: always 2× the original byte count. A 1 KB binary becomes a 2 KB hex string.
  • Base64: approximately 1.33× (4 characters per 3 bytes), rounded up to the nearest 4-character block with padding. A 1 KB binary becomes roughly 1.37 KB base64.

Concretely, for a 256-byte hash digest: hex produces 512 characters; base64 produces 344 characters (including padding). Base64 is about 33% more compact than hex, which matters at scale — for example when embedding thousands of thumbnails as data URIs or transmitting bulk cryptographic material over a rate-limited API.

URL Safety Considerations

Standard base64 uses + and /, both of which are reserved characters in URLs. If you embed standard base64 in a query string without encoding it, + gets interpreted as a space and / can break path parsing.

The solution is Base64url (RFC 4648 §5), which replaces + with - and / with _ and omits padding:

function toBase64url(base64) {
  return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}

// Node.js shortcut
Buffer.from('Hello').toString('base64url'); // 'SGVsbG8'
Enter fullscreen mode Exit fullscreen mode

Hex, by contrast, uses only characters that are already URL-safe, so no transformation is needed. This is one reason hex is common in URL tokens and API keys where developers want zero ambiguity.

Use Cases: When to Choose Each

Choose Hex When:

  • Displaying cryptographic output — hash digests (MD5, SHA-256), HMAC signatures, and key fingerprints are nearly always shown in hex. The format is human-readable and pairs naturally with debugging tools.
  • Logging and auditing — hex strings are easy to grep, diff, and compare visually, even in monospace terminals.
  • Color codes — CSS hex colors (#ff6600) are a specialised subset of hex encoding.
  • Low-level protocol work — network packet dumps, bytecode, and memory addresses are conventionally hex.

Choose Base64 When:

  • Data URIs — embedding images, fonts, or other binary assets directly in HTML/CSS requires base64. Browsers understand data:image/png;base64,... natively.
  • Email attachments (MIME) — the MIME standard specifies base64 for encoding binary email attachments.
  • JSON payloads containing binary — base64 is the idiomatic way to carry binary blobs (certificates, avatars, audio clips) inside JSON without escaping every byte.
  • JWTs — JSON Web Tokens use Base64url for both the header/payload sections and the signature.
  • Bandwidth-sensitive applications — when you must encode large volumes of binary data as text, base64's ~33% overhead beats hex's 100% overhead.

Performance Considerations

In most applications encoding speed is not the bottleneck, but for completeness: hex encoding is marginally faster to encode and decode because the per-byte operation is a simple 4-bit shift and lookup, with no grouping logic. Base64 must group 3 bytes at a time and handle padding edge cases. On modern hardware the difference is negligible for typical payload sizes (kilobytes to low megabytes), but if you're encoding gigabytes of streaming data, hex's simplicity wins.

A Quick Decision Flowchart

  • Need to embed in a URL without percent-encoding? → Base64url or hex
  • Need to embed binary in JSON or HTML? → Base64
  • Need to display a hash for human verification? → Hex
  • Minimising encoded size is critical? → Base64
  • Simplest possible implementation? → Hex

Try It Yourself

Use the DevPlaybook Base64 Encoder/Decoder to convert text or files to base64 and back, and the Hash Generator to see SHA-256 and MD5 output in hex format side by side. For a deeper dive into base64 specifically, see our Base64 Encoding Explained guide.

Want these tools available offline? The DevToolkit Bundle ($9 on Gumroad) packages 40+ developer tools into a single downloadable kit — no internet required.

Conclusion

Base64 vs hex encoding comes down to context: hex is readable, debuggable, and universally safe in URLs — but doubles your data size. Base64 is more compact and essential for MIME and data URIs — but needs URL-safe variants in some contexts. Know the trade-offs and you'll reach for the right tool every time.

Free Developer Tools

If you found this article helpful, check out DevToolkit — 40+ free browser-based developer tools with no signup required.

Popular tools: JSON Formatter · Regex Tester · JWT Decoder · Base64 Encoder

🛒 Get the DevToolkit Starter Kit on Gumroad — source code, deployment guide, and customization templates.

Top comments (0)