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.
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.
=
as padding:==
; remainder 2 bytes → end with =
.Value | Char | Value | Char | Value | Char | Value | Char |
---|---|---|---|---|---|---|---|
0 | A | 16 | Q | 32 | g | 48 | w |
1 | B | 17 | R | 33 | h | 49 | x |
2 | C | 18 | S | 34 | i | 50 | y |
3 | D | 19 | T | 35 | j | 51 | z |
4 | E | 20 | U | 36 | k | 52 | 0 |
5 | F | 21 | V | 37 | l | 53 | 1 |
6 | G | 22 | W | 38 | m | 54 | 2 |
7 | H | 23 | X | 39 | n | 55 | 3 |
8 | I | 24 | Y | 40 | o | 56 | 4 |
9 | J | 25 | Z | 41 | p | 57 | 5 |
10 | K | 26 | a | 42 | q | 58 | 6 |
11 | L | 27 | b | 43 | r | 59 | 7 |
12 | M | 28 | c | 44 | s | 60 | 8 |
13 | N | 29 | d | 45 | t | 61 | 9 |
14 | O | 30 | e | 46 | u | 62 | + |
15 | P | 31 | f | 47 | v | 63 | / |
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 =
.
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==
语言 | 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 |