Home  >  Article  >  Backend Development  >  C# Base64 encoding function

C# Base64 encoding function

黄舟
黄舟Original
2016-12-22 13:55:122018browse

1. Base64 encoding rules
The idea of ​​Base64 encoding is to use 64 basic ASCII characters to re-encode the data. It splits the data that needs to be encoded into a byte array. In groups of 3 bytes. Arrange the 24-bit data in order, and then divide the 24-bit data into 4 groups, that is, 6 bits in each group. Then add two 0s before the highest bit of each group to make up one byte. This re-encodes a 3-byte group of data into 4 bytes. When the number of bytes of data to be encoded is not an integral multiple of 3, that is to say, the last group is not enough 3 bytes when grouping. At this time, 1 to 2 0 bytes are filled in the last group. And add 1 to 2 "=" at the end after the final encoding is completed.

Example: BASE64 encoding of ABC:
1. First get the ASCII code value corresponding to ABC. A (65) B (66) C (67);
2. Then take the binary value A (01000001) B (01000010) C (01000011);
3. Then connect the binary codes of these three bytes (010000010100001001000011 );
4. Then divide it into 4 data blocks in units of 6 bits, and fill the highest bit with two 0s to form a 4-byte encoded value, (00010000) (00010100) (00001001) (00000011), The blue part is the real data;
5. Then convert these four bytes of data into decimal numbers to get (16) (20) (9) (3);
6. Finally, the 64 given by BASE64 Basic character table, find the corresponding ASCII code character (Q) (U) (J) (D). The value here is actually the index of the data in the character table.

Note: BASE64 character table: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

2. Decoding rules
The decoding process is to restore 4 bytes to 3 bytes and then rearrange the byte array into data according to different data forms.

3. Implementation 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 the C# Base64 encoding function. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn