我編寫了這個python代碼,試圖將對象轉換爲一個零的字符串,但解碼失敗,因爲數據不能取消。這是代碼:Python編碼函數無法解碼
def encode(obj):
'convert an object to ones and zeros'
def tobin(str):
rstr = ''
for f in str:
if f == "0": rstr += "0000"
elif f == "1": rstr += "0001"
elif f == "2": rstr += "0010"
elif f == "3": rstr += "0100"
elif f == "4": rstr += "1000"
elif f == "5": rstr += "1001"
elif f == "6": rstr += "1010"
elif f == "7": rstr += "1100"
elif f == "8": rstr += "1101"
elif f == "9": rstr += "1110"
else: rstr += f
return rstr
import pickle, StringIO
f = StringIO.StringIO()
pickle.dump(obj, f)
data = f.getvalue()
import base64
return tobin(base64.b16encode(base64.b16encode(data)))
def decode(data):
def unbin(data):
rstr = ''
for f in data:
if f == "0000": rstr += "0"
elif f == "0001": rstr += "1"
elif f == "0010": rstr += "2"
elif f == "0100": rstr += "3"
elif f == "1000": rstr += "4"
elif f == "1001": rstr += "5"
elif f == "1010": rstr += "6"
elif f == "1100": rstr += "7"
elif f == "1101": rstr += "8"
elif f == "1110": rstr += "9"
return rstr
import base64
ndata = base64.b16decode(base64.b16decode(unbin(data)))
import pickle, StringIO
f = StringIO.StringIO(ndata)
obj = pickle.load(f)
return obj
你知道Python有內置的'bin()'函數嗎? – 2010-07-01 19:12:39
他的二進制字符串轉換有些損壞(例如0100 <-> 3) – 2010-07-01 19:21:34
@Tim Pietzcker:'tobin'沒有執行二進制轉換。 – jdmichal 2010-07-01 19:22:13