X Xerobit

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.

Mian Ali Khalid · · 4 min read
Use the tool
Base64 Encoder / Decoder
Encode and decode Base64 strings and files. Client-side, safe for sensitive data.
Open Base64 Encoder / Decoder →

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 caseChoose
SHA-256/SHA-512 hash outputHex (convention)
HMAC signatures, API keysHex
JWT tokensBase64URL
Image/PDF data URIsBase64
JSON API binary fieldsBase64 (33% smaller)
Database storage of hashesHex (readable in SQL queries)
Color codes, MAC addressesHex
Email attachments (MIME)Base64

Related posts

Related tool

Base64 Encoder / Decoder

Encode and decode Base64 strings and files. Client-side, safe for sensitive data.

Written by Mian Ali Khalid. Part of the Encoding & Crypto pillar.