All articles
165 articles · updated weekly See our Tools
All articles
Comparisons

Base64 vs Hex: Difference, Size and When to Use Each

Hex doubles the size of your bytes; Base64 adds about 33%. See the difference, a size table for tokens and when to use each in logs, databases and URLs.

Base64 vs Hex: Difference, Size and When to Use Each
COVER · Comparisons

On a session-token project, I had to choose between Base64 and hexadecimal for storing 32 random bytes. I picked Base64 because the string was shorter, created a VARCHAR(44) column in MySQL with the default collation, and moved on. Months later, reviewing the schema, I noticed that token lookups ignored case, and Base64 is case-sensitive. Two different tokens could be treated as the same one. No incident came of it, but the "trivial" decision had a hole no size comparison will show you.

Both formats represent the same bytes; what changes is the alphabet, the size, and where each one misbehaves. This post compares Base64 and hex for someone who has to pick one: the difference in numbers, a size table for tokens, what happens in databases, URLs and logs, and a decision rule. What Base64 is and how it works internally is in what is Base64; here the focus is the comparison.

The difference between Base64 and hex

Both live in the same standard, RFC 4648, which defines Base16 (hex), Base32 and Base64. The difference is how many bits each character carries:

  • Hex (Base16): 16 symbols (0-9, a-f), 4 bits per character. Each byte becomes exactly two characters. Output size: 2 × n.
  • Base64: 64 symbols (A-Z, a-z, 0-9, +, /), 6 bits per character. Every 3 bytes become 4 characters, with = padding when the input isn't a multiple of 3. Output size: 4 × ceil(n / 3).

So hex doubles the size (100% overhead) and Base64 adds about 33%. The same 32 bytes:

hex:       fb3fbf3e8a4c2d99e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f7   (64 characters)
Base64:    +z+/PopMLZng8aKzxNXm9wgZKjtMXW5/gJGis8TV5vc=                       (44 characters)
Base64URL: -z-_PopMLZng8aKzxNXm9wgZKjtMXW5_gJGis8TV5vc                        (43 characters)

I generated those three lines with Node 22's Buffer from the same bytes. Note the padding: 32 bytes are 10 full groups of 3 (30 bytes, 40 characters) plus 2 leftover bytes, which become 3 characters and one =. Two = only appear when 1 byte is left over (16 and 64 bytes, for example).

Size table for tokens

The most common token sizes, checked by actually running the encoding:

Bytes Typical use Hex Base64 Base64URL without =
16 UUID, short token 32 24 (==) 22
20 SHA-1 40 28 (=) 27
32 SHA-256, session token 64 44 (=) 43
64 SHA-512 128 88 (==) 86

Libraries already know this. In Python, secrets.token_hex(32) returns 64 characters and secrets.token_urlsafe(32) returns 43. Entropy is the same in both: 256 bits. The format doesn't make a token stronger or weaker, only longer or shorter.

Where hex wins

Databases with case-insensitive comparison. This is the argument I hadn't considered. In MySQL, the server's default collation is utf8mb4_0900_ai_ci, and _ci means case-insensitive. I tested it on MySQL 8.4 with a VARCHAR(44) column and a UNIQUE key:

INSERT INTO sessions VALUES ('q83vEjRWeJA=', 1);
SELECT user_id FROM sessions WHERE token = 'Q83VEJRWEJA=';
-- returns 1: the uppercase token "found" the session of a different value
INSERT INTO sessions VALUES ('Q83VEJRWEJA=', 2);
-- ERROR 1062: Duplicate entry 'Q83VEJRWEJA=' for key 'sessions.token'

In Base64, q and Q are different values; to the collation they're the same letter. The practical collision risk with 256 random bits is small, but the lookup is semantically wrong and effective entropy drops. With hex the problem disappears, because a3 and A3 really are the same byte. If you're storing Base64 as text in MySQL, declare the column with a binary collation (CHARACTER SET ascii COLLATE ascii_bin); in the same test, the ascii_bin table accepted both tokens as distinct. In PostgreSQL the default collations are already case-sensitive, but the best option in both databases is something else: store the raw bytes (BINARY(32) in MySQL, BYTEA in PostgreSQL) and encode only at the edge, when the value leaves the system.

Human reading and hashes. Hashes are shown in hex by convention: the SHA-256 you compare against the one published on a download page is 64 hex characters, and sha256sum prints it that way. Each pair of characters is one byte, so you can count length, compare prefixes and spot a difference between two values by eye. That's why the hash generator outputs hex, and why hashing 101 shows every example in that format. The same goes for byte dumps (xxd, hexdump), memory addresses and CSS colors (#1e90ff is three bytes in hex).

Tools that already speak hex. decode('...', 'hex') in PostgreSQL, UNHEX() in MySQL, bytes.fromhex() in Python. No variant to choose and no padding to remember.

Where Base64 wins

Size in a text channel. Cookies, HTTP headers, JSON, data URIs. A 1 MB file becomes about 1.33 MB in Base64 and 2 MB in hex. For attachments and embedded images, hex isn't a serious option.

When the protocol requires it. JWT, PEM, MIME attachments, Authorization: Basic, data URIs: someone already chose the format, and it's Base64 or Base64URL.

URLs, with the right variant. Standard Base64 has + and /, which mean something else in a URL. The Base64URL variant (RFC 4648, section 5) swaps them for - and _. A detail many people get wrong: the RFC doesn't mandate removing =; it says padding may be omitted when the length is known. What requires Base64URL without padding is JWT (RFC 7515). So when you build a token for a URL, decide explicitly whether your format carries = and document it. Hex is immune here: it only has safe characters.

In JavaScript, converting bytes to both forms:

const bytes = crypto.getRandomValues(new Uint8Array(32));

// hex
const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');

// Base64 and Base64URL (the spread is fine for 32 bytes; not for large files)
const b64 = btoa(String.fromCharCode(...bytes));
const b64url = b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

String.fromCharCode(...bytes) passes each byte as a function argument; with a few hundred KB it blows the stack (I tried 200 KB on Node 22: Maximum call stack size exceeded). For files, use the methods in how to convert Base64.

Base64 or hex: how to decide

The rule I use now, after the collation scare:

  1. Store bytes as bytes. BINARY/BYTEA in the database, and encode only on the way out. That removes the question for storage.
  2. If you must store text in a database with case-insensitive comparison, use hex (or force a binary collation).
  3. If a human will read, compare or paste it, use hex. Hashes, checksums, IDs in logs.
  4. If the value crosses a URL, cookie or header and size matters, use Base64URL, and document whether it carries padding.
  5. If the protocol defines the format, follow it. JWT is Base64URL without =, period.

Changing later is expensive: a token already issued in Base64 can't become hex without a migration or accepting both formats for a while. Choose based on where the value will be used most, not where it's born. To test the round trip before standardizing, the Base64 Encoder has a URL-safe mode and shows the difference right away.

Frequently asked questions

What is the difference between Base64 and hex?

Both turn bytes into text. Hex uses 16 symbols and spends 2 characters per byte (doubling the size); Base64 uses 64 symbols and spends 4 characters per 3 bytes (about 33% more). Hex is more readable and case-insensitive; Base64 is more compact.

How many characters is a 32-byte token?

64 in hex, 44 in Base64 (with one trailing =) and 43 in Base64URL without padding. Entropy is the same in all three formats: 256 bits.

Is Base64 encryption?

No. Neither Base64 nor hex hides anything: anyone can decode them without a key. They're ways of writing bytes as text, not of protecting them.

Can I store a Base64 token in a MySQL VARCHAR column?

Yes, as long as the column uses a binary collation (ascii_bin or utf8mb4_bin). With the default collation, which is case-insensitive, tokens that differ only in case are treated as equal. Better still: store it in BINARY(32).

Hex for people and databases, Base64 for transport

Base64 and hex carry the same bytes and the same entropy; the choice is about where the string will live. Hex is larger but readable, has no variants and is immune to case-insensitive comparison, which makes it the safe choice for hashes, logs and text columns. Base64 saves a third of the space and is the format JWT, MIME and data URIs require, as long as you use the URL variant for URLs and remember the database may not tell q from Q. And if you can store the raw bytes, store the raw bytes.

HT
Author
Hugo Tanaka
Second-generation Japanese-Brazilian who grew up watching his father debug logistics spreadsheets in BASIC. Full-stack developer focused on tooling and DX — the role that finally brought code, writing and an obsession with productivity into one place. Writes for people who already know how to code and need to solve a problem now.
View profile