python - 得到当使用多个字节作为输入运行下面的 text_from_bytes 函数时
问题描述
该函数应获取与任意字节数等效的字符串并打印该结果。当我输入一个字节时,代码返回字符串值。当我如下所示输入多个字节时,会发生 ValueError。如何修改函数以允许多个字节?
def text_from_bytes(bytes, encoding='utf-8', errors='surrogatepass'):
n = int(bytes, 2)
print(n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding,
errors) or '\0')
convert = "01000001 01000010"
text_from_bytes(convert)
解决方案
int
不知道如何解析包含空格的字符串。在调用 int 之前尝试过滤掉空间。
def text_from_bytes(bytes, encoding='utf-8', errors='surrogatepass'):
n = int(bytes.replace(" ", ""), 2)
print(n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding,
errors) or '\0')
convert = "01000001 01000010"
text_from_bytes(convert)
结果:
AB