Discuss / Python / DIY

DIY

Topic source

久疤_796

#1 Created at ... [Delete] [Delete and Lock User]
``````import base64
import sys
L = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/']
def myencode(s):
res = []
last = 0
n = 0
if isinstance(s,bytes):
for i in s:
t = (last<<8) + i
n += 2
res += [ord(L[t>>n])]
last = t % (1<<n)
if n==6:
res += [ord(L[last])]
n = 0
last = 0
if n:
res += [ord(L[last<<(6-n)])]
res += [ord('=')]*((-len(res))%4)
return bytes(res)
#获取函数名，并eval为函数
if isinstance(s,str):
self = eval((lambda:sys._getframe(1).f_code.co_name)())
return self(s.encode())
raise TypeError('argument must be \'bytes\' or \'str\' but \'%s\' was given'%s.__class__.__name__)
t = 'Just a test!.'.encode()
print(myencode(t))
print(base64.b64encode(t))
t = myencode(t)

def mydecode(s):
if isinstance(s,bytes):
while s[-1]==ord(b'='):
s = s[:-1]
last = 0
n = 0
res = []
for i in s:
n = 6 if n==0 else n-2
last = (last<<6) + L.index(chr(i))
if n!=6:
res += [(last>>n)]
last = last%(1<<n)
return bytes(res)
raise TypeError('need \'bytes\' but %s'%type(s))
s = '德玛西亚'
t = s.encode()
a = myencode(t)
b = mydecode(a)
print('测试：')
print('字符串：',s)
print('bytes:',t)
print('编码:',a,base64.b64encode(t)==a)
print('解码：',b,base64.b64decode(a)==b)
print('转字符串:',b.decode(),b.decode()==s)
``````

• 1