【发布时间】:2018-06-19 01:07:48
【问题描述】:
我正在尝试使用 struct 包使用 python 将 char 打包为字节,但使用此代码打包 char 时我的代码不会返回 4 个字节:
def charToHex(s):
#check if string is unicode
if isinstance(s, str):
print(struct.pack('<c', 'a'.encode(encoding='utf-8')))
return '{:02x}'.format(struct.unpack('<I', struct.pack('<c', s.encode('utf-8')))[0])
#check if input is already a byte
elif isinstance(s, bytes):
return '{:02x}'.format(struct.unpack('<I', struct.pack('<c', s))[0])
else:
raise Exception()
谁能向我解释为什么这不起作用?我只是想将 unicode char 转换为 4 个字节并解压缩它,但它甚至不会正确打包。
【问题讨论】:
-
cformat 是 C 意义上的单个字节的char,而不是 Python 意义上的 Unicode 代码点。由于 Unicode 字符的 UTF-8 编码介于 1 到 4 个字节之间,因此您不能将pack用作c。您必须做一些愚蠢的事情,例如将其填充到 4 个字节并将其打包为4c(此时使用 UTF-32 而不是 UTF-8 要简单得多)。
标签: python struct unicode byte