【汇顶科技笔试】编程题
题目:Base64编码
text = input().strip() text = [ord(x) for x in text] #获取ASCII数组 index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" rest = len(text) % 3 #转成二进制字符串 bi = "" for str in text: curStr = format(str, '#010b')[2:] bi += curStr #二进制转索引,先看看是否需要扩充 inds = list() if len(bi) % 6 != 0: for i in range(len(bi), (len(bi)//6 + 1)*6): bi += "0" for i in range(0, len(bi), 6): cur = int(bi[i:i+6], 2) inds.append(cur) #查询索引得到最终结果 res = '' for ind in inds: res += index[ind] if rest > 0: for i in range(3-rest): res += "=" print(res)