Base64 Fundamentals

1. What is Base64 encoding

Base64 is a way to represent binary data using 64 printable characters (A-Z, a-z, 0-9, +, /). Since 2^6 = 64, Base64 encodes data in 6-bit units.

2. Why use Base64

In many cases you need to transmit or store binary data as text, for example in URLs, JSON, forms, and emails. Base64 contains only printable characters and avoids the string terminator \0, preventing truncation when binary data is treated as a string.

3. Encoding rules (highlights)

Base64 index table

Value Char Value Char Value Char Value Char
0A16Q32g48w
1B17R33h49x
2C18S34i50y
3D19T35j51z
4E20U36k520
5F21V37l531
6G22W38m542
7H23X39n553
8I24Y40o564
9J25Z41p575
10K26a42q586
11L27b43r597
12M28c44s608
13N29d45t619
14O30e46u62+
15P31f47v63/

If the number of bytes is not a multiple of 3, pad zeros at the end before encoding: 1-byte remainder → append ==; 2-byte remainder → append =.

4. Examples

Example 1: bytes 0 1 2
Binary: 0011 0000 · 0011 0001 · 0011 0010 → group by 6 bits → 12, 3, 4, 50 → chars M D E y
Result: MDEy

Example 2 (with padding): bytes 0 1 2 3
Groups: 12, 3, 4, 50, 12, 48 (zero padded at the end) → chars M D E y M w
Result: MDEyMw==

5. Base64 encode/decode across languages

语言 Base64 编码 Base64 解码
Java base64 = new BASE64Encoder().encode(str.getBytes()); str = new String(new BASE64Decoder().decodeBuffer(base64));
JavaScript base64 = btoa(str);
var s = CryptoJS.enc.Utf8.parse(str);
base64 = CryptoJS.enc.Base64.stringify(s);
str = atob(base64);
var s = CryptoJS.enc.Base64.parse(base64);
str = s.toString(CryptoJS.enc.Utf8);
PHP $base64 = base64_encode($str); $str = base64_decode($base64);
C#/.NET byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
base64 = System.Convert.ToBase64String(bytes);
byte[] bytes = System.Convert.FromBase64String(base64);
str = System.Text.Encoding.UTF8.GetString(bytes);
Python import base64\nbase64 = base64.b64encode(str) import base64\nstr = base64.b64decode(base64)
Perl use MIME::Base64;\n$base64 = encode_base64($str); use MIME::Base64;\n$str = decode_base64($base64);
Golang import b64 "encoding/base64" import b64 "encoding/base64"\nstr := b64.StdEncoding.DecodeString(base64)
Ruby require "base64"\nbase64 = Base64.encode64(str) require "base64"\nstr = Base64.decode64(base64)
MySQL/MariaDB SELECT TO_BASE64(str); SELECT FROM_BASE64(base64);
PostgreSQL SELECT encode(str, 'base64'); SELECT decode(base64, 'base64');
Linux Shell $ echo test | base64 $ echo dGVzdA== | base64 -d