base64 乱码_什么是base64

Base64是一种用64个characters(a-z,A-Z,0-9,+,/)来表示任意二进制数据的方法。

用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要让记事本这样的文本处理软件能处理二进制数据,就需要一个二进制到字符串的转换方法。Base64是一种最常见的二进制编码方法。

Base64的原理很简单,首先,准备一个包含64个字符table

59334644660547127e615e869c79b42a.png

规则(以“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:

  1. https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576
  2. https://www.cnblogs.com/antineutrino/p/3756106.html
  3. https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值