I. Coding rules for BASE64
The idea of BASE64 encoding is to re-encode the data using 64 basic ASCII characters. It splits the data that needs to be encoded into a byte array. A group of 3 bytes. The 24-bit data is sorted sequentially, and the 24 bits of data are divided into 4 groups, 6 bits per group. Then fill in a byte with two 0 in front of the highest bit of each group. This re-encodes a 3-byte set of data into 4 bytes. When the number of bytes of data to encode is not an integral multiple of 3, that is, the last group is less than 3 bytes at the time of grouping. At this point the last group is populated with 1 to 2 0 bytes. and add 1 to 2 "=" At the end after the last encoding is complete.
Example: ABC will be BASE64 encoded:
1, first take the ASCII code value of the ABC corresponding. A (+) B (+) C (67);
2, then take the binary value A (01000001) B (01000010) C (01000011);
3, then the three bytes of the binary code to connect (010000010100001001000011);
4, then 6 bits of the unit into 4 data blocks, and the highest bit filled two 0 after the formation of 4 bytes of the encoded value, (00010000) (00010100) (00001001) (00000011), where the blue part of the real data;
5, then the four bytes of data into 10 binary numbers (16) (20) (9) (3);
6, finally according to the BASE64 given 64 basic character table, the corresponding ASCII code character (Q) (U) (J) (D), where the value is actually the data in the character list index.
Note: BASE64 character: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/
Two. Decoding rules
The decoding process is to restore 4 bytes to 3 bytes and then rearrange the byte arrays into data according to different data forms.
Three. implementations in C #
byte[] bytes = Encoding.Default.GetBytes("helloworld");
string str = Convert.ToBase64String(bytes);
Console.WriteLine(str);
Console.ReadLine();
//base 64 decode
bytes = Convert.FromBase64String(str);
Console.WriteLine(Encoding.Default.GetString(bytes));
Console.ReadLine();
The above is the content of C # Base64 encoding function, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!