SoFunction
Updated on 2025-03-07

C# Base64 encoding function

1. Base64 encoding rules
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 byte arrays. Take 3 bytes as a group. Arrange the 24-bit data in order, and then divide the 24-bit data into 4 groups, that is, each group has 6 bits. Then add two 0 before the highest bit of each group to make up one byte. This re-encodes a 3-byte set of data into 4 bytes. When the number of bytes of the data to be encoded is not an integer multiple of 3, that is, the last group is not enough for 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 last encoding is complete.

Example: ABC will be BASE64 encoding:
1. First, take 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 (010000010100001001000100011);
4. Then divide it into 4 data blocks in units of 6 bits, and then fill two 0s in the highest bit to form the encoded value of 4 bytes, (00010000) (00010100) (00001001) (00000011), where the blue part is the real data;
5. Then convert these four bytes of data into decimal numbers to (16) (20) (9) (3);
6. Finally, based on the 64 basic character table given by BASE64, the corresponding ASCII code characters (Q) (U) (J) (D) are found. 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 reorganize the byte array into data according to different data forms.

Implementation in C#
Copy the codeThe code is as follows:

byte[] bytes = ("helloworld");
string str = Convert.ToBase64String(bytes);
(str);
();
//base 64 decode
bytes = Convert.FromBase64String(str);
((bytes));
();