When to use Base64 vs hexadecimal encoding — a practical comparison with code examples for hashes, binary data, and cryptographic keys.
Hex (hexadecimal) represents each byte as two hex digits (0–9, a–f). One byte = two characters.
Binary: 01001000 01100101 01101100
Hex: 48 65 6c
Result: "48656c" ("Hel")
| Input size | Hex size | Base64 size |
|---|---|---|
| 16 bytes | 32 chars | 24 chars |
| 32 bytes | 64 chars | 44 chars |
| 1 KB | 2 KB | ~1.37 KB |
Base64 is ~33% larger than binary; Hex is 100% larger. Base64 is more space-efficient.
#ff57330x7fff5fbff...// Hex encoding (Node.js)
const hex = Buffer.from('Hello').toString('hex'); // '48656c6c6f'
const back = Buffer.from(hex, 'hex').toString(); // 'Hello'
// SHA-256 hash as hex (Web Crypto)
const data = new TextEncoder().encode('hello');
const hash = await crypto.subtle.digest('SHA-256', data);
const hashHex = Array.from(new Uint8Array(hash), b => b.toString(16).padStart(2, '0')).join('');
Rule of thumb: Use hex for debugging and human-readable crypto outputs; use Base64 for transmitting binary data in text protocols.