Reprinted from: http://www.cnblogs.com/hongru/archive/2012/01/14/2321397.html
"Base64"
-base64 are encoded in string lengths, in groups of 8bit characters per 3.
-Then for each group, first get the ASCII encoding for each character,
-then convert the ASCII encoding to 8bit binary to get a set of 3*8=24bit bytes
-then divide the 24bit into 4 6bit bytes and fill two high 0 in front of each 6bit byte to get 4 8bit bytes
-The 4 8bit bytes are then converted to 10, and the corresponding encoded characters are obtained against the BASE64 encoded table (table below).
(Note: 1.) The encoding character is required to be 8bit, so it must be within the ASCII encoding range, \U0000-\U00FF, Chinese is not.
2. If the encoded character length is not a multiple of 3, then use 0 instead of the corresponding output character =)
| BASE64 Coding Table |
| 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 |
21st |
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 |
/
|
For example, the following 2 examples:
A) If the character length is divisible by 3: For example "Tom":
T o m
ASCII: 109 111
8bit bytes: 01010100 01101111 01101101
6bit bytes: 010101 000110 111101 101101
Decimal: 6 45
Corresponding code: V G 9 t
So, Btoa (' Tom ') = vg9t
b) string lengths cannot be divisible by 3, such as "Lucy":
L u c y
ASCII: 117 121
8bit bytes: 01001100 01110101 01100011 01111001 00000000 00000000
6bit bytes: 010011 000111 010101 100011 011110 010000 000000 000000
Decimal: 7 (Exception) (Exception)
Corresponding code: T H V J e Q = =
Since Lucy has only 4 letters, so by 3 groups, the second group has two vacancies, so it needs to be filled with a zero. Here it is necessary to note that, because it is necessary to make up the 0, so the conversion into a decimal time can not be used in accordance with the regular Base64 encoding table to correspond, so not a, can be understood as a special "anomaly", the code should correspond to "=".
With the above theory, it is easy for us to implement a Base64 code.
[codec] on the principle and implementation of Base64 coding