Base64 vs Hex Encoding — When to Use Each
Compare Base64 and hex encoding for binary data. Learn which is more compact, when to use each in APIs, cryptography, and storage, with JavaScript and Python examples.
Base64 and hex both encode binary data as ASCII text. Base64 is 33% larger than the original; hex is 100% larger. Choose based on readability, tooling, and context — not habit.
Encode and decode Base64 with the base64 decoder and encoder.
Size comparison
Original binary: 3 bytes = 24 bits
Hex output: 6 chars = 100% overhead (2 hex chars per byte)
Base64 output: 4 chars = 33% overhead (4 chars per 3 bytes)
Example: SHA-256 hash (32 bytes)
Hex: 64 characters → "e3b0c44298fc1c149afb..."
Base64: 44 characters → "47DEQpj8HBSa+/TImW+5..."
Base64 is always more compact than hex for the same binary data.
When to use hex
Hex is preferred when human readability of raw bytes matters:
// Cryptographic hashes — hex is the convention:
import { createHash } from 'crypto';
const hash = createHash('sha256').update('hello').digest('hex');
// "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
// Easy to compare visually, standard in security tools
// Hex also used for:
// - Color codes: #ff5733
// - MAC addresses: 00:1A:2B:3C:4D:5E
// - Byte-level debugging
// - Cryptographic keys and signatures in most security protocols
import hashlib
# Python: hashlib outputs hex by default
h = hashlib.sha256(b"hello").hexdigest()
# "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
# Convert between hex and bytes:
raw = bytes.fromhex(h) # hex → bytes
back = raw.hex() # bytes → hex
When to use Base64
Base64 is preferred when compactness and transport compatibility matter:
// Data URIs — Base64 fits in HTML/CSS without escaping:
const img = `<img src="data:image/png;base64,${base64String}">`;
// JWT tokens use Base64URL (URL-safe variant of Base64):
// eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMSJ9.signature
// JSON API responses — hex works too, but Base64 is 33% smaller:
res.json({ file: buffer.toString('base64') }); // compact
res.json({ file: buffer.toString('hex') }); // verbose but readable
Base64URL vs standard Base64
Regular Base64 uses + and /, which break in URLs. Base64URL replaces them:
// Standard Base64 — breaks in URLs:
// "abc+def/ghi==" → + and / need escaping in URLs
// Base64URL — safe for URLs and filenames:
function toBase64URL(str) {
return Buffer.from(str)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, ''); // Remove padding
}
// Node.js 16+:
const encoded = Buffer.from('hello world').toString('base64url');
// "aGVsbG8gd29ybGQ" — no +, /, or =
Convert between Base64 and hex
// Base64 → hex:
function base64ToHex(base64) {
return Buffer.from(base64, 'base64').toString('hex');
}
// Hex → Base64:
function hexToBase64(hex) {
return Buffer.from(hex, 'hex').toString('base64');
}
// SHA-256 hash as Base64 (for Content-Security-Policy hashes):
import { createHash } from 'crypto';
const scriptContent = "alert('hello')";
const hash = createHash('sha256').update(scriptContent).digest('base64');
// CSP: script-src 'sha256-...'
console.log(`'sha256-${hash}'`);
import base64, binascii
# Base64 → hex:
raw = base64.b64decode("aGVsbG8=")
hex_str = binascii.hexlify(raw).decode() # "68656c6c6f"
# Hex → Base64:
raw = binascii.unhexlify("68656c6c6f")
b64_str = base64.b64encode(raw).decode() # "aGVsbG8="
Decision guide
| Use case | Choose |
|---|---|
| SHA-256/SHA-512 hash output | Hex (convention) |
| HMAC signatures, API keys | Hex |
| JWT tokens | Base64URL |
| Image/PDF data URIs | Base64 |
| JSON API binary fields | Base64 (33% smaller) |
| Database storage of hashes | Hex (readable in SQL queries) |
| Color codes, MAC addresses | Hex |
| Email attachments (MIME) | Base64 |
Related tools
- Base64 Encoder/Decoder — encode/decode Base64
- Hash Generator — SHA-256, MD5 output in hex
- URL Encoder — encode Base64URL for URLs
Related posts
- Base64: How It Actually Works Under the Hood — Base64 is everywhere — in JWTs, data URLs, email attachments. This is the byte-l…
- When You Should NOT Use Base64 Encoding — Base64 is the duct tape of the web — and like real duct tape, it's used in place…
- Base64 Encoding on the Command Line — Linux, macOS, and Windows — Encode and decode Base64 on the command line using base64, openssl, and PowerShe…
- Base64 Image Encoding — Embed Images in HTML, CSS, and JSON — Base64 image encoding converts image files to text strings for embedding in HTML…
- Base64 in Node.js — Buffer, btoa, and Streaming Large Files — Node.js provides Buffer for Base64 encoding/decoding and native btoa/atob since …
Related tool
Encode and decode Base64 strings and files. Client-side, safe for sensitive data.
Written by Mian Ali Khalid. Part of the Encoding & Crypto pillar.