Base64 & Binary Encoding Cheat Sheet
Quick reference for Base64 and binary encoding: padding, URL-safe variants, hexadecimal, binary, and common conversion patterns.
Base64 encodes arbitrary bytes into a 64-character ASCII alphabet so data survives text-only channels (JSON, URLs, email). It is not encryption; it roughly inflates size by 33%. Binary and hexadecimal are the two other interchangeable byte representations.
The Base64 Alphabet
Uses A–Z, a–z, 0–9, +, /, padded with =. RFC 4648 defines the standard and URL-safe variants.
| Type | Alphabet | + → | / → | Padding |
|---|---|---|---|---|
| Standard | A-Z a-z 0-9 + / | + | / | = required |
base64url | A-Z a-z 0-9 - _ | - | _ | often omitted |
hello → aGVsbG8=
hi → aGk=
> ~ binary → Pj4g
0x00 0x01 → AAE=
How Encoding Works
Three input bytes (24 bits) become four Base64 characters (6 bits each). If the input length is not a multiple of 3, the last block is padded with = to reach a multiple of 4 output characters.
import base64
data = b"hello world"
encoded = base64.b64encode(data) # 'aGVsbG8gd29ybGQ='
decoded = base64.b64decode(encoded)
# URL-safe, no padding
urlsafe = base64.urlsafe_b64encode(data).rstrip(b"=")
# CLI
printf 'hello' | base64 # aGVsbG8=
echo 'aGVsbG8=' | base64 -d # hello
// Browser
const encoded = btoa("hello"); // aGVsbG8=
const decoded = atob(encoded); // hello
Binary vs Hexadecimal vs Base64
| Representation | Per byte | Example of byte 0x3F | Size |
|---|---|---|---|
| Binary | 8 bits | 00111111 | 8× |
| Hexadecimal | 4 bits | 3F | 2× |
| Base64 | 6 bits | Pw== | ~1.33× |
Conversions:
value = 0b00111111 # 63
hex(value) # '0x3f'
bin(value) # '0b111111'
bytes([value]) # b'?'
Base64 in URLs & Data URIs
base64url replaces + and / with - and _ so the string is safe in URLs and filenames without escaping.
# Data URI for embedding small images
data:image/png;base64,iVBORw0KGgo...
# Standard vs URL-safe
data+with+chars → data-with-chars
Common Pitfalls
| Pitfall | Fix |
|---|---|
| Missing padding throws in strict decoders | Ensure length is a multiple of 4, or use a tolerant decoder. |
+// corrupted in URLs | Use base64url (or decode with str.replace('+','-').replace('/','_')). |
| Whitespace/newlines in encoded data | Strip before decoding. |
btoa with non-Latin1 characters | UTF-8 encode first: btoa(unescape(encodeURIComponent(s))). |
| Treating Base64 as encryption | It is encoding — always add encryption for confidentiality. |