Skip to content

Base64 编码

Table RFC 4648

Index Binary Char Index Binary Char Index Binary Char Index Binary Char
0 000000 A 16 010000 Q 32 100000 g 48 110000 w
1 000001 B 17 010001 R 33 100001 h 49 110001 x
2 000010 C 18 010010 S 34 100010 i 50 110010 y
3 000011 D 19 010011 T 35 100011 j 51 110011 z
4 000100 E 20 010100 U 36 100100 k 52 110100 0
5 000101 F 21 010101 V 37 100101 l 53 110101 1
6 000110 G 22 010110 W 38 100110 m 54 110110 2
7 000111 H 23 010111 X 39 100111 n 55 110111 3
8 001000 I 24 011000 Y 40 101000 o 56 111000 4
9 001001 J 25 011001 Z 41 101001 p 57 111001 5
10 001010 K 26 011010 a 42 101010 q 58 111010 6
11 001011 L 27 011011 b 43 101011 r 59 111011 7
12 001100 M 28 011100 c 44 101100 s 60 111100 8
13 001101 N 29 011101 d 45 101101 t 61 111101 9
14 001110 O 30 011110 e 46 101110 u 62 111110 +
15 001111 P 31 011111 f 47 101111 v 63 111111 /
Padding =

Example

\[ 3\times8=4\times6 \]
  1. 3 字节,每个字节 8bit,共 24bit,base64 分割 4 次,每次 6bit,并转化为 4 字节,每个字节为 2 个00+6bit
  2. 2 字节,16bit 分割 3 次,3 字节,前 2 次 6bit 同 1,最后 1 次 4bit,开头补00,结尾补00,最后补=达到 4 字节
  3. 1 字节,8bit 分割 2 次,第 1 次 6bit 同 1,第 2 次 2bit,开头补00,结尾补0000,最后补==达到 4 字节

"hel"

  1. ord(c) Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
  2. bin(x) Convert an integer number to a binary string prefixed with “0b”.
>>> ord('h'), bin(ord('h'))
(104, '0b1101000')
>>> ord('e'), bin(ord('e'))
(101, '0b1100101')
>>> ord('l'), bin(ord('l'))
(108, '0b1101100')
>>> raw = '01101000'+'01100101'+'01101100'
>>> int(raw[:6], 2), int(raw[6:12], 2), int(raw[12:18], 2), int(raw[18:24], 2)
(26, 6, 21, 44)

(26, 6, 21, 44)查表aGVs,验证:

>>> import base64
>>> base64.b64encode(b'hel')
b'aGVs'

"lo"

>>> ord('l'), bin(ord('l'))
(108, '0b1101100')
>>> ord('o'), bin(ord('o'))
(111, '0b1101111')
>>> raw = '01101100'+'01101111'
>>> int(raw[:6], 2), int(raw[6:12], 2), int('00'+raw[12:16]+'00', 2)
(27, 6, 60)

(27, 6, 60)查表bG8,不足 4 字节补=bG8=,验证:

>>> base64.b64encode(b'lo')
b'bG8='

"a"

>>> ord('a'), bin(ord('a'))
(97, '0b1100001')
>>> raw = '01100001'
>>> int(raw[:6], 2), int('00'+raw[6:8]+'0000', 2)
(24, 16)

(24, 16)查表YQ,不足 4 字节补==YQ==,验证:

>>> base64.b64encode(b'a')
b'YQ=='

Comments