Base64是一种用64个characters(a-z,A-Z,0-9,+,/)来表示任意二进制数据的方法。
用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要让记事本这样的文本处理软件能处理二进制数据,就需要一个二进制到字符串的转换方法。Base64是一种最常见的二进制编码方法。
Base64的原理很简单,首先,准备一个包含64个字符table
规则(以“MENON”举例):
1. 每3个characters一组,既“MEN”,因为每个character 是 8 bits所以我们有(8 * 3) 24 bits.
2. 然后把24bits除以6 = 4 blocks. (为什么是6?) 因为2^6 = 64(a-z,A-Z,0-9,+,/) characters.
3. 把每一个blocks根据base64的table转换成相应的character,第二步我们得到了4个blocks,所以会转换成4个characters。
4. 然后剩下的两个characters “ON”,会有8*2=16bits,然后16/6= 2blocks,余数是4bits,因为这4bits不足一个block所需的6bits,所以我们用两个0来补齐。
5. 最后我们还要用=的表明,最后一组characters是不足3个的,缺几个就几个=,因为ON是2个chars,相对于3个缺一个所以补一个=。
Example
1. Convert “MENON” into its (8 bit) binary state format. Take each characters of the string and write its 8 – bit binary representation.
ASCII values of characters in string to be encoded
M : 77 (01001101), E : 69 (01000101),
N : 78 (01001110), O : 79 (01001111), N : 78 (01001110)
resultant binary data of above string is :
01001101 01000101 01001110 01001111 01001110
2. Starting from left make blocks of 6 bits until all bits are covered
BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (1110)
3. If the rightmost block is less than 6 bits just append zeros to the right of that block to make it 6 bits. Here in above example we have to appended 2 zeros to make it 6.
BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (111000)
Notice the bold zeros.
4. Take 3 characters from input_str (“MEN”) i.e 24 bits and find corresponding decimal value (index to char_set).
BLOCKS :
INDEX --> (010011) : 19, (010100) : 20, (010101) : 21, (001110) : 14
char_set[19] = T, char_set[20] = U, char_set[21] = V, char_set[14] = O
So our input_str = “MEN” will be converted to encoded string “TUVO”.
5. Take remaining characters (“ON”). We have to pad resultant encoded string with 1 “=” as number of characters is less than 3 in input_str. (3 – 2 = 1 padding)
BLOCKS :
INDEX --> (010011) : 19 (110100) : 52 (111000) : 56
char_set[19] = T char_set[52] = 0 char_set[56] = 4
So our input_str = "ON" will be converted to encoded string "T04=".
reference:
- https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576
- https://www.cnblogs.com/antineutrino/p/3756106.html
- https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/