Base64 vs Hex Encoding
Base64 and hexadecimal (hex) are both methods of representing binary data as text strings. They are used in different contexts and have different trade-offs in terms of output size, readability, and compatibility. This guide explains how each works and when to use each one.
How They Work
Base64
Encodes every 3 bytes of binary data into 4 ASCII characters using a 64-character alphabet (A–Z, a–z, 0–9, +, /). Output size is approximately 33% larger than the input.
Example: Hello → SGVsbG8=
Hexadecimal
Encodes every byte as exactly 2 hex characters (0–9, a–f). Output size is exactly 2× the input size. Each hex character represents 4 bits (a nibble).
Example: Hello → 48656c6c6f
Size Comparison
Base64 Size
Output is ~133% of input size. 3 bytes → 4 characters. A 100-byte input produces ~136 characters of Base64.
Hex Size
Output is exactly 200% of input size. 1 byte → 2 characters. A 100-byte input produces exactly 200 hex characters.
Winner for size: Base64 — Base64 is more compact than hex for the same binary data.
Readability
Neither format is human-readable for arbitrary binary data, but hex has an advantage for specific use cases:
- Hex is easier to read for byte-level inspection — each pair of characters is exactly one byte
- Hex is preferred for displaying cryptographic hashes, memory addresses, and color codes
- Base64 output looks like random text and is harder to inspect manually
When to Use Base64
- Embedding images, fonts, or files in HTML, CSS, or JSON
- Encoding email attachments (MIME encoding)
- Passing binary data through APIs that only accept text
- JWT token encoding (header and payload are Base64URL encoded)
- HTTP Basic Authentication credentials
- Data URLs in web applications
When to Use Hex
- Displaying cryptographic hash values (MD5, SHA-256, SHA-512)
- Representing color codes in CSS and design tools (
#ff5733) - Memory addresses and binary file inspection
- Cryptographic keys and initialization vectors (IVs)
- Network packet analysis and debugging
- UUID and GUID representation
Base64URL — A URL-Safe Variant
Standard Base64 uses + and / characters which have special meaning in URLs. Base64URL replaces + with - and / with _, making it safe for use in URLs and filenames without percent-encoding. JWT tokens use Base64URL encoding for their header and payload sections.
Quick Reference
Use Base64 for
- File/image embedding
- API binary transfer
- JWT tokens
- Email attachments
Use Hex for
- Hash display
- Color codes
- Crypto keys
- Byte inspection
Use JSONHack's free Base64 encoder and decoder — instant, browser-based, private.