【问题标题】:Encoding error when converting Hex to Base64 Python将 Hex 转换为 Base64 Python 时出现编码错误
【发布时间】:2016-03-30 02:06:04
【问题描述】:

我目前正在开始使用 python,并编写一个程序,该程序将转换给定的长字符串十六进制数字,应该分成对。我很难使用 python 编码功能。

到目前为止,我有:

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 部分的编码/解码有什么问题。

【问题讨论】:

    标签: python encoding


    【解决方案1】:

    您的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))
    

    【讨论】:

    • 感谢您的解决方案。我很难理解 base64 部分的功能,比如它如何使用以及它用作参数的方式。文档有点难以理解,但现在我明白了。
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2012-12-20
    • 2021-08-22
    相关资源
    最近更新 更多