On the principle of Base64 coding and its implementation methods sharing _ related skills

Source: Internet
Author: User
Tags base64 base64 encode prev
First, Base64 coding principle

Step 1: Convert all characters to ASCII code;
Step 2: Convert the ASCII code into a 8-bit binary;
Step 3: The binary 3 grouped into a group (less than 3 in the back of 0) a total of 24, and then split into 4 groups, each group of 6 bits;
Step 4: Unify the 6-bit binary before filling two 0 to fill 8 bits;
Step 5: Convert the binary of the complement 0 to decimal;
Step 6: Obtain the decimal corresponding BASE64 encoding from the Base64 coding table;



Description: Less than 3 0 of the final Base64 encoding =, rather than a!

Two, Base64 coding example

Example one: Zyq corresponds to BASE64 encoded as ENLX


Example two: Mzwu corresponding BASE64 encoding for bxp3dq==



Although in addition to IE, most modern browsers have supported native based Base64 encode and decode, such as Btoa and Atob. (Save Canvas Canvas as IMG and force change mimetype for download, next record)

But curiosity still drives me to understand the Base64 coding principle. So that it can be implemented under IE that does not support native base64 encoding.

"Base64"
The-BASE64 encoding is in the string length, a group of every 3 8bit characters,
-Then for each group, first get the ASCII encoding for each character,
-then converts the ASCII encoding into a 8bit binary, resulting in a set of 3*8=24bit bytes
-then divide the 24bit into 4 6bit bytes and fill in two highs 0 in front of each 6bit byte, and get 4 8bit bytes
-then convert the 4 8bit bytes into 10, and compare the encoded characters against the BASE64 encoding table (the following table).

(Note: 1.) Requires that the encoded character be 8bit, so it must be within the ASCII coding range, \U0000-\U00FF, Chinese is not good.
2. If the encoded character length is not a multiple of 3, it is replaced with 0, 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, give the following 2 examples:
A the length of the character is divisible by 3: For example, "Tom":

Copy Code code as follows:

T o m
ASCII:84 111 109
Bit bytes: 01010100 01101111 01101101
Bit bytes: 010101 000110 111101 101101
Decimal: 21 6 61 45
Corresponding code: V G 9 T

So, Btoa (' Tom ') = vg9t
b The string length cannot be divisible by 3, such as "Lucy":
Copy Code code as follows:

L u c y
ASCII:76 117 99 121
Bit bytes: 01001100 01110101 01100011 01111001 00000000 00000000
Bit bytes: 010011 000111 010101 100011 011110 010000 000000 000000
Decimal: 19 7 21 35 30 16 (Exception) (Exception)
Corresponding code: T H V J e Q = =

Because Lucy is only 4 letters, so according to the 3 groups, the second group has two vacancies, so need to use 0来 to be padded. Here we need to pay attention to, because it is necessary to make up the 0, so the conversion into a decimal can not be used as a general Base64 coding table to correspond, so not a, can be understood to become a special "anomaly", the encoding should correspond to "=".
With the above theory, it is easy for us to implement a Base64 code.
Copy Code code as follows:

/**
* Base64 Encoding & Decoding
* For fixing browsers which don ' t support Base64 | Btoa |atob
*/
(function (win, undefined) {
var Base64 = function () {
var base64hash = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/';
Btoa method
function _btoa (s) {
if (/([^\u0000-\u00ff])/.test (s)) {
throw new Error (' Invalid_character_err ');
}
var i = 0,
Prev
Ascii
MoD
result = [];
while (I < s.length) {
ASCII = S.charcodeat (i);
MoD = i% 3;
Switch (MoD) {
The first 6-bit only requires 8-bit binary to move to the right two-bit
Case 0:
Result.push (Base64hash.charat (ASCII >> 2));
Break
Second 6-bit = First 8-bit two-digit + second 8-digit top 4
Case 1:
Result.push (Base64hash.charat (prev & 3) << 4 | (ASCII >> 4));
Break
Third 6-bit = Second 8-bit 4-digit + third 8-digit top 2
4th 6 digits = Third 8-bit after 6
Case 2:
Result.push (Base64hash.charat (prev & 0x0f) << 2 | (ASCII >> 6));
Result.push (Base64hash.charat (ASCII & 0x3f));
Break
}
prev = ASCII;
i + +;
}
At the end of the loop, look at the MoD, for 0 proofs need to fill 3 6 bits, the first one for the last 8-bit last two digits after 4 0. The other two 6 digits correspond to the abnormal "=";
MoD is 1, the proof also needs to fill two 6 bits, one is the last 8 bit 4 bit two 0, another corresponding exception "="
if (mod = 0) {
Result.push (Base64hash.charat (prev & 3) << 4));
Result.push (' = = ');
else if (mod = 1) {
Result.push (Base64hash.charat (prev & 0x0f) << 2));
Result.push (' = ');
}
Return Result.join (");
}
Atob method
The idea of reversing encode can be
function _atob (s) {
s = S.replace (/\s|=/g, "");
var cur,
Prev
MoD
i = 0,
result = [];
while (I < s.length) {
cur = base64hash.indexof (S.charat (i));
MoD = i% 4;
Switch (MoD) {
Case 0:
Todo
Break
Case 1:
Result.push (String.fromCharCode (prev << 2 | cur >> 4));
Break
Case 2:
Result.push (String.fromCharCode (prev & 0x0f) << 4 | cur >> 2));
Break
Case 3:
Result.push (String.fromCharCode (prev & 3) << 6 | cur));
Break
}
prev = cur;
i + +;
}
Return Result.join (");
}
return {
Btoa: _btoa,
Atob: _atob,
Encode: _btoa,
Decode: _atob
};
}();
if (!win. BASE64) {win. Base64 = Base64}
if (!win.btoa) {Win.btoa = Base64.btoa}
if (!win.atob) {Win.atob = Base64.atob}
}) (window)

Base64 Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.