Encoding

Base64 vs Hex: Differences and When to Use Each

Both Base64 and hex encode binary data as text, but they're built for different purposes. Base64 prioritizes compactness. Hex prioritizes human readability at the byte level. Choosing the wrong one can break APIs, cause parse errors, and confuse downstream systems.

What Both Actually Do

Binary data (bytes) cannot safely travel through systems designed for text — email, JSON, URLs, HTML. Both encodings solve this by representing each byte as printable ASCII characters:

Same bytes, two encodings:
Input: bytes [72, 101, 108, 108, 111] ("Hello")
Hex: 48656c6c6f
Base64: SGVsbG8=
32-byte SHA-256 hash:
Hex (64 chars):
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Base64 (44 chars):
LPJNul+wow4m6Dsqxbnmo4Hg/UoZ44/9JK4mLa1eJQ=

Size Comparison

EncodingCharacters usedOverhead1 byte becomes1 MB becomes
Hex16 (0-9, a-f)100%2 chars~2 MB
Base6464 (A-Z, a-z, 0-9, +, /)~33%1.33 chars avg~1.33 MB
Raw binaryN/A (not text-safe)0%1 byte1 MB

Base64 uses 33% more space than raw binary. Hex uses 100% more (doubles the size). For anything embedded in JSON or HTML, Base64 is preferred over hex for this reason.

Feature Comparison

PropertyHexBase64
Character set0-9, a-f (16 chars)A-Z, a-z, 0-9, +, / (64 chars)
Size overhead100% (2 chars/byte)~33% (4 chars/3 bytes)
Human readableYes — each pair = one byteNo — bytes span multiple chars
URL safe?Yes — all hex chars are URL safeNo — + and / need encoding
PaddingNone needed= signs added for alignment
VariantsUppercase (A-F) or lowercase (a-f)Standard, URL-safe (-, _), MIME
Used forHashes, colors, byte debuggingFile embeds, auth headers, JWT
Browser APINo native hex encode/decodebtoa() / atob() for strings
RFCNo specific RFC (common convention)RFC 4648
Padding charsNone= (sometimes omitted in URL-safe)

When to Use Each

Use Hex for...
  • • Cryptographic hashes (MD5, SHA-1, SHA-256) — the de-facto standard
  • • CSS colors (#ff6b6b)
  • • Debug output — easy to see each byte at a glance
  • • Binary protocol inspection (Wireshark, hex dumps)
  • • API keys and tokens that need URL safety
  • • HMAC signatures in HTTP headers (X-Signature)
Use Base64 for...
  • • Embedding binary files in JSON, XML, or HTML
  • • Data URIs (data:image/png;base64,...)
  • • HTTP Authorization headers (Basic dXNlcjpwYXNz)
  • • MIME email attachments
  • • JWT tokens (header + payload encoded as Base64url)
  • • TLS/SSL certificates (PEM format)

Code Examples

JavaScript

// Base64 encode/decode (browser)
const encoded = btoa('Hello'); // "SGVsbG8="
const decoded = atob(encoded); // "Hello"
// Hex encode (no built-in — use Buffer or manual)
const hex = Buffer.from('Hello').toString('hex');
// "48656c6c6f"
// Crypto (SHA-256 → hex, the standard)
const hash = await crypto.subtle.digest('SHA-256', data);
const hex = [...new Uint8Array(hash)]
.map(b => b.toString(16).padStart(2, '0')).join('');

Python

import base64, hashlib
# Base64
encoded = base64.b64encode(b'Hello') # b'SGVsbG8='
decoded = base64.b64decode(encoded) # b'Hello'
# Hex
hex_str = b'Hello'.hex() # '48656c6c6f'
# SHA-256 → hex (standard)
h = hashlib.sha256(b'Hello').hexdigest()

Frequently Asked Questions

Is Base64 secure?

No. Base64 is encoding, not encryption. It is completely reversible without a key. Anyone can decode Base64 instantly. It is used to safely transmit binary data through text channels, not to protect data. For security, use AES-256 encryption or SHA-256 hashing (one-way). The fact that it looks like random characters does not make it secure.

Why do JWTs use Base64url instead of standard Base64?

Standard Base64 uses + and / which are special characters in URLs. JWT puts the encoded header and payload directly in the URL (or Authorization header). Base64url replaces + with - and / with _, and omits = padding, making JWTs safe to use in URLs and HTTP headers without percent-encoding. Standard Base64 decoders will reject - and _ as invalid.

Can I use hex for storing SHA-256 hashes in a database?

Yes, and it is the most common approach. A SHA-256 hash is 32 bytes. As hex, it becomes a 64-character string. Store it as CHAR(64) or VARCHAR(64). Alternatively, store as raw BINARY(32) for 50% storage savings. Never store hashes as Base64 in databases — hex is the convention for hash strings and easier to compare visually.

Why does Base64 have = padding?

Base64 encodes 3 bytes into 4 characters. When the input length is not a multiple of 3, padding = is added to make the output a multiple of 4 characters. 1 leftover byte gets == padding; 2 leftover bytes get one = padding. Some implementations (URL-safe Base64, JWTs) omit padding because the length can be inferred from context.

Key Takeaways

  • Both convert binary data to text — neither is encryption.
  • Base64 is ~33% overhead; hex is 100% overhead — Base64 is more compact.
  • Use hex for hashes, colors, and byte-level debugging.
  • Use Base64 for file embeds, auth headers, and JWT tokens.
  • Base64url (JWTs) replaces + with - and / with _ for URL safety.

Related Resources