Base64 Encoding Explained: From 3 Bytes to 4 Characters

X LinkedIn Facebook

Disclaimer: This article is general technical guidance. Never paste production credentials, customer data or private keys into a tool you have not verified runs locally in your browser.

Open a browser console and type this:

btoa("中文")
// Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window':
// The string to be encoded contains characters outside of the Latin1 range.

Nothing in that message is wrong. 中文 is perfectly valid text, and btoa is the browser's built-in Base64 encoder. Yet the function refuses to run. The reason is the single most useful fact about Base64, and it explains the three bugs people hit most often: Base64 does not encode characters. It encodes bytes.

By the end of this article you will be able to encode any string by hand, predict where the = signs appear, and know why a Chinese character and a Latin letter behave differently inside the same function. Every claim below can be checked with three lines of code, so the derivations are not there to be trusted — they are there to be verified.

The short version: Base64 reads input three bytes at a time (24 bits), slices those bits into four groups of six, and prints one ASCII character per group. Six bits can express 64 values, hence the 64-character alphabet in RFC 4648. When fewer than three bytes remain, the missing bits are filled with zeros and the gap is reported with = padding.

The First Step Is UTF-8, Not Base64

The error above is a type error in disguise. btoa predates Unicode in the browser and was written to accept Latin-1: characters whose code points fit in one byte, 0–255. 中 is U+4E2D, which is 20013 in decimal. That number cannot be represented in a byte, so the function stops rather than silently truncating it.

The fix is to do the conversion the browser will not do for you: turn the string into bytes using UTF-8, then feed the bytes to btoa. UTF-8 is the rule that decides how many bytes a character occupies, and the rule is worth seeing in binary, because Base64 is about to slice those bits.

中 is a three-byte character in UTF-8. The leading 1110 on the first byte announces "three-byte sequence"; the following bytes all begin with 10, which marks them as continuations:

Byte Hex Binary Payload bits carried
1stE4111001000100 (prefix 1110)
2ndB810111000111000 (prefix 10)
3rdAD10101101101101 (prefix 10)

So a Chinese character is not "one character of input" to Base64. It is three bytes, which is exactly one full Base64 round. That is why Chinese text encodes to a string about a third longer than the source, and why a single emoji — four bytes — produces eight output characters plus padding.

new TextEncoder().encode("中")
// Uint8Array(3) [ 228, 184, 173 ]  ->  E4 B8 AD

Six Bits at a Time: Why 3 Bytes Become 4 Characters

Take the word Man. Three bytes, 24 bits. Base64 cuts that bit string into four slices of six bits each, and each slice is used as an index into the alphabet.

Step Value Binary
M = 0x4D7701001101
a = 0x619701100001
n = 0x6E11001101110
Concatenated (24 bits): 01001101 01100001 01101110
Group 119010011 → T
Group 222010110 → W
Group 35000101 → F
Group 446101110 → u

The output is TWFu. No key, no table lookup beyond the one below, and no ambiguity: any decoder that shares the alphabet gets Man back.

The 64-character alphabet

RFC 4648 fixes the order. Uppercase first, then lowercase, then digits, then + and /. Memorising the first two rows is enough to hand-encode most ASCII text, because ASCII letters land on the same letters in the output.

Index +0 +1 +2 +3 +4 +5 +6 +7
0ABCDEFGH
8IJKLMNOP
16QRSTUVWX
24YZabcdef
32ghijklmn
40opqrstuv
48wxyz0123
56456789+/

The same algorithm, fed with bytes

Now run the identical procedure on 中. The input is the three bytes from the earlier table, not the character:

Step Hex Binary
Byte 1E411100100
Byte 2B810111000
Byte 3AD10101101
Concatenated (24 bits): 11100100 10111000 10101101
Group 157111001 → 5
Group 211001011 → L
Group 334100010 → i
Group 445101101 → t

The answer is 5Lit. It looks nothing like 5Lit's source, and that is the point of the format — but the arithmetic never changed. Only the bytes did. If you want to check it the other way round, paste 5Lit into the Base64 encoder and decoder, switch to decode mode, and the tool returns 中.

Padding Is Arithmetic, Not Decoration

Base64 consumes three bytes per round and prints four characters per round. Inputs are rarely a multiple of three, so the last round is usually short. The = signs exist to tell the decoder how short.

Input Bytes Bits Final round Output
Man324complete, 4 groupsTWFu
Ma2163 groups + 2 zero bits, 1 char shortTWE=
M182 groups + 4 zero bits, 2 chars shortTQ==
Hello540one full round + 2 bytesSGVsbG8=

Follow Ma through. M is 01001101, a is 01100001, so the 16 real bits are 01001101 01100001. Slicing gives 010011 (19 → T), 010110 (22 → W), and a third slice holding only four real bits: 0001. Those are padded with two zeros to make a full six-bit index, 000100 = 4 → E. The fourth character cannot be formed at all, so it is replaced by =. Result: TWE=.

One remaining byte gives two = signs for the same reason in reverse: only two six-bit groups can be formed, so two characters are missing. M alone becomes TQ==.

This is why strict decoders reject unpadded input. Without =, a decoder cannot distinguish "the encoder removed padding for URL use" from "the string was truncated in transit". Dropping the padding is legal in the URL-safe variant, which is a different alphabet. Standard Base64 prints + and /; Base64URL prints - and _, because a + inside a query string is read as a space and a / is a path separator. The three-way comparison of Base64, Base64URL and percent-encoding sits in the scheme table inside Base64 Is Not Encryption.

Sanity check: a valid standard Base64 string is always a multiple of four characters long, counting the padding. If it is not, either padding was stripped or the string is not Base64 at all.

An Emoji Crosses Four Bytes

Emoji are where the "characters versus bytes" split becomes impossible to ignore. 😀 is U+1F600, which UTF-8 writes as four bytes. Four bytes is not a multiple of three, so the final round is short by two bytes and ends in ==.

UTF-8 bytes Binary Six-bit groups Output
F0 9F 9811110000 10011111 1001100060, 9, 62, 24 → 8 J + Y8J+Y
80 (1 byte left)1000000032, 0 → g A, then ==gA==
Full output8J+YgA==

Eight characters for one visible symbol. The same holds for any non-Latin script: the encoded length tracks the byte count, and the byte count tracks the UTF-8 encoding, not the number of glyphs a reader perceives.

Verify It Yourself

Four snippets, four runtimes. Each one prints the values used in this article, so a mismatch immediately tells you which assumption broke.

JavaScript: the wrong way and the right way

// Wrong: btoa treats the argument as Latin-1 and rejects anything above U+00FF.
btoa("中");   // InvalidCharacterError

// Right: convert to UTF-8 bytes, then hand each byte to btoa as a character.
const bytes = new TextEncoder().encode("中");          // [228, 184, 173]
const encoded = btoa(String.fromCharCode(...bytes));   // "5Lit"

// Round trip back to text.
const decoded = new TextDecoder().decode(
  Uint8Array.from(atob("5Lit"), (c) => c.charCodeAt(0))
);                                                     // "中"

Note the spread: String.fromCharCode maps each byte to a single character, and TextDecoder reverses it. For long inputs, chunk the array instead of spreading a million arguments at once.

Python

import base64

base64.b64encode("中".encode("utf-8")).decode()   # '5Lit'
base64.b64decode("5Lit").decode("utf-8")          # '中'
base64.b64encode("😀".encode("utf-8")).decode()   # '8J+YgA=='

Node.js

Buffer.from("中", "utf8").toString("base64");   // '5Lit'
Buffer.from("5Lit", "base64").toString("utf8"); // '中'
Buffer.from("Ma", "utf8").toString("base64");   // 'TWE='

The by-hand result, as one comparison

[ "Man", "Ma", "M", "中", "😀" ].map(s =>
  Buffer.from(s, "utf8").toString("base64")
);
// [ 'TWFu', 'TWE=', 'TQ==', '5Lit', '8J+YgA==' ]

The Four Bugs Behind Almost Every Base64 Complaint

Symptom Cause Fix
btoa throws InvalidCharacterError The string contains code points above 255, so it is not Latin-1 Run it through TextEncoder first, then encode the resulting bytes
Decoded text reads as 中 or ä The bytes are UTF-8, but they were decoded as Latin-1 Decode with UTF-8: TextDecoder(), .decode("utf-8"), or toString("utf8")
Decoder says "invalid length" or throws on a correct-looking string Padding was stripped, usually by a URL-safe encoder Restore = to the next multiple of four, or use a URL-safe decoder
A + in the string arrives as a space Query-string parsing treats + as an encoded space Use the URL-safe alphabet, or percent-encode the value before sending it
An embedded image will not render Line breaks inside the data URI, or the wrong MIME type in the prefix Strip whitespace and check that data:image/png;base64, matches the real format

All five reduce to the same sentence: know which layer you are fixing. Text to bytes is UTF-8. Bytes to printable text is Base64. Bytes to secrecy is neither, and confusing those three layers is what turns a small encoding bug into a security incident.

Frequently Asked Questions

Why does btoa reject Chinese characters?

btoa only accepts characters whose code points are 255 or below, because its historical job was to wrap Latin-1 text. Chinese characters live far above that range, so btoa rejects the input before encoding anything. Convert the string to UTF-8 bytes with TextEncoder first, then pass those bytes to btoa one character at a time.

Is Base64 the same thing as UTF-8?

No. UTF-8 decides how characters become bytes; Base64 decides how bytes become ASCII text. They stack: text is first encoded as UTF-8 bytes, then those bytes are encoded as Base64. Skipping the first step is what produces mojibake and btoa errors.

Why does my Base64 string end with one or two equals signs?

Because Base64 consumes three bytes per round, and every round prints four characters. When the input is not a multiple of three bytes, the final round has spare bits, and the = signs tell the decoder how many of the last group's bits are real. One spare byte produces ==, two spare bytes produce a single =.

Does Base64 work on characters or on bytes?

On bytes, always. The same string in two different encodings produces two different Base64 outputs, which is why fixing the text encoding is the first step of every Base64 bug. An emoji is four UTF-8 bytes, so it produces eight Base64 characters including padding, not one.

Methodological note: This article was written and fact-checked by the Fengvi Editorial Team following a documented editorial methodology. Every derivation was reproduced with Node.js 24 (Buffer) and Chromium (TextEncoder, btoa) before publication; the byte-level examples follow RFC 4648 and RFC 3629.