[英]Encoding error when converting Hex to Base64 Python
I am currently beginning python, and writing a program that will convert a given long string of hex numbers, that should be separated into pairs. 我目前正在开始使用python,并编写一个程序来转换给定的十六进制数字长字符串,该字符串应成对出现。 I am having a hard time utilizing pythons encoding function.
我在利用pythons编码功能时遇到了困难。
So far, I have: 到目前为止,我有:
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"))
I can get it to print [b'I', b"'", b'm', b'm', b'm', b' ', b' ',.....]
but I am not sure what is wrong with my encode/decode to base64 section of the bytesToBase64()
method. 我可以打印
[b'I', b"'", b'm', b'm', b'm', b' ', b' ',.....]
但我不是确定我对bytesToBase64()
方法的base64部分进行编码/解码有什么问题。
Your bytesToBase64
function returns a list of bytes represented by the given hex string (garbled a little bit because you used insert
instead of append
). 您的
bytesToBase64
函数返回由给定的十六进制字符串表示的字节列表(有点乱码,因为您使用insert
而不是append
)。 You haven't done the base64 encoding part. 您尚未完成base64编码部分。
To fix your existing function: 修复现有功能:
def bytesToBase64(str):
b64List = []
stringsByTwo = splitByTwo(str.upper())
for x in stringsByTwo:
b64List.append(base64.b16decode(x))
print base64.b64encode("".join(b64List))
But this function is not very idiomatic. 但是这个功能不是很习惯。 To completely rewrite it:
要完全重写它:
def bytesToBase64(s):
return base64.b64encode(binascii.unhexlify(s))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.