Comparison
Base64 vs Hex: When to Use Each Encoding for Binary Data
TL;DR
| Base64 | Hex | |
|---|---|---|
| Output size (3 bytes in) | 4 characters (~33% overhead) | 6 characters (~100% overhead) |
| Alphabet | A-Z, a-z, 0-9, +, / (64 chars) | 0-9, A-F (16 chars) |
| Readability | Poor — 'SGVsbG8' is 'Hello' but you can't tell by looking | Good — each byte is exactly 2 chars, easy to spot patterns |
| Primary use | Email attachments, JWT, data URIs, API key encoding | Crypto hashes, memory dumps, debug output, color codes |
| Variants | Standard (+/=), URL-safe (-_), MIME (76-char wrap) | Lowercase/uppercase, with or without 0x prefix, with or without spaces |
The options in depth
Base64
The compact transport encoding — 4 characters per 3 bytes.
Good for
- ·Embedding binary in JSON/XML/text protocols
- ·JWT token encoding
- ·Data URIs (data:image/png;base64,...)
- ·Email attachments
Avoid when
- ·Debugging or inspecting raw data (Hex is better)
- ·Very short payloads — the = padding adds overhead
- ·When the format requires an even number of chars per byte (e.g., CSS colors)
Hex
The human-readable byte representation — 2 characters per byte.
Good for
- ·Cryptographic hashes (SHA-256, MD5)
- ·Debugging and memory/disk dumps
- ·C/C++ byte array literals (0x41, 0x42)
- ·CSS color values
Avoid when
- ·Large binary payloads — Base64 is 2× more compact
- ·Bandwidth-sensitive transport (IoT, embedded)
- ·Embedded data in high-throughput APIs
Which one should you pick?
→ I'm building a REST API — should I use Base64 or Hex for binary payloads?
Base64 — it's the industry standard (JWT, CloudFormation, Terraform, OAuth2 client credentials). Use the URL-safe variant without padding if the payload goes into query strings.
→ I'm reading a SHA-256 hash from a log file. Is it Base64 or Hex?
Hex — cryptographic hashes are almost always displayed as hex because it's the human-readable convention. If it's 64 characters using only 0-9 and a-f, it's hex. If it's ~44 characters with mixed-case letters, it might be Base64.
Common pitfalls
- ⚠Base64 = padding adds trailing = characters that break JSON if not properly handled by the parser. Always verify your JSON parser handles = without issues.
- ⚠Not all Base64 implementations agree on the alphabet — URL-safe uses - and _ instead of + and /. Always specify which variant you're using.
- ⚠Hex with 0x prefix (e.g., 0xFF) is a notation, not an encoding. 0x is a programmer's convention; it's not part of the hex value. Don't confuse it with the actual encoded output.
Frequently Asked Questions
How much smaller is Base64 than Hex?
Exactly 50% smaller. Hex produces 2 characters per input byte; Base64 produces ~1.33 characters per input byte. 2 ÷ 1.33 = 1.5, so Hex is 50% larger than Base64 for the same input.
Can I convert Base64 to Hex directly?
Yes — decode the Base64 to bytes first, then encode the bytes as hex. The conversion is lossless both ways. Example: 'SGVsbG8=' (Base64) → bytes → '48656c6c6f' (Hex).