![](/img/trans.png)
[英]hex codec / base64 encoding in PHP (converting from python)
[英]Encoding error when converting Hex to Base64 Python
我目前正在开始使用python,并编写一个程序来转换给定的十六进制数字长字符串,该字符串应成对出现。 我在利用pythons编码功能时遇到了困难。
到目前为止,我有:
import base64
def splitByTwo(str):
return [i+j for i,j in zip(list(str)[::2], list(str)[1::2])]
def bytesToBase64(str):
b64List = []
stringsByTwo = splitByTwo(str.upper())
for x in stringsByTwo:
b64List.insert(stringsByTwo.index(x), base64.b16decode(x))
return b64List
print(bytesToBase64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"))
我可以打印[b'I', b"'", b'm', b'm', b'm', b' ', b' ',.....]
但我不是确定我对bytesToBase64()
方法的base64部分进行编码/解码有什么问题。
您的bytesToBase64
函数返回由给定的十六进制字符串表示的字节列表(有点乱码,因为您使用insert
而不是append
)。 您尚未完成base64编码部分。
修复现有功能:
def bytesToBase64(str):
b64List = []
stringsByTwo = splitByTwo(str.upper())
for x in stringsByTwo:
b64List.append(base64.b16decode(x))
print base64.b64encode("".join(b64List))
但是这个功能不是很习惯。 要完全重写它:
def bytesToBase64(s):
return base64.b64encode(binascii.unhexlify(s))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.