Standard Base64 algorithm description, base64 Algorithm Description
Author: zhanhailiang Date: 2014-12-19
Algorithm Description:
Base64 requires that each three 8-bit bytes be converted into four 6-bit bytes (38 = 46 = 24), and then 6-bit bytes are added with two more 0 bits to form four 8-bit bytes. That is to say, the converted string is theoretically 1/3 longer than the original one.
- The first character shifts two places to the right to obtain the location of the Base64 table of the first target character. Based on this value, the corresponding character on the table is the first target character.
- Then, perform the (&) operation on the first character and 0x03 (00000011), move the second character four places to the left, and then move the second character to the right four places to the former or (| ), that is, the second target character is obtained.
- Then, the second character and 0x0f (00001111) are operated with (&) and shifted to 2 places left. Then the third character is shifted to 6 places with the former or (| ), obtain the third target character.
- Finally, the third character and 0x3f (00111111) are connected with (&) to obtain the fourth target character.
After each of the preceding steps, perform the AND operation on the result AND 0x3F to get the encoded characters.
The remaining bytes continue to be converted separately according to the encoding rules (1 to 2, 2 to 3; 0 to complete the number of digits is not enough), and then fill in 4 bytes with the = sign. This is why some Base64 encoding ends with one or two equal signs, but the equal signs can only be two at most. Because:
At least two target bytes are generated for an original byte.
Therefore, the remainder can only be one of the three numbers 0, 1, and 2 in any case. If the remainder is 0, it indicates that the number of original bytes is exactly a multiple of 3 (ideally ). If it is 1, it is converted into two Base64 encoded characters. In order to make Base64 encoding a multiple of 4, we need to add two equal signs. Similarly, if it is 2, we need to add one equal sign.
The above algorithm description Reference from: http://baike.baidu.com/link? Url = lriFEiUvmROqg0a0R0DZS0t8gEmIQRnJ13eSGZuYFFOyUDSrhY824dE7zjTbhSA5rpp2NiDn2-mCoLPbPlY1q _ #3_3
Algorithm Implementation:
The implementation method of base64_encode is extracted from PHP/ext/standard/base64.c. The Code is as follows: https://github.com/billfeller/billfeller.github.io/tree/master/code/base64
Test:
[root@~/wade/git/billfeller.github.io/code/base64]# gcc -o base64 base64.c [root@~/wade/git/billfeller.github.io/code/base64]# ./base64 "abcd*"YWJjZCo=[root@~/wade/git/billfeller.github.io/code/base64]# /usr/local/php/bin/php -r 'echo base64_encode("abcd*").PHP_EOL;'YWJjZCo=