我的目标是在Python中将地址字符串转换为打包数据。例如:
address = '7fffde53bf80' #input
formated = '\x80\xbf\x53\xde\xff\x7f' #desired output
我写了一个简单的脚本来完成这个。
x = range(len(address))
evn = [e for e in x if e % 2 == 0][::-1] #reverse the list
formated = ''
i = 0
while(i < len(evn)):
formated = formated + r'\x' + address[evn[i]:evn[i] + 2]
i = i + 1
print formated
我确信在python中有更好的方法可以做到这一点。谁能建议我怎么做?
答案 0 :(得分:3)
使用str.decode()
将十六进制值解码为字节,然后反转:
address.decode('hex')[::-1]
演示:
>>> address = '7fffde53bf80'
>>> address.decode('hex')[::-1]
'\x80\xbfS\xde\xff\x7f'