Python 2.7和3.6中struct.unpack的行为差异

2024-06-07 14:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将代码库从Python2.7转换为Python3.6。我有以下代码:

import struct 

unpacked = struct.unpack('<BI6s', '\x02\xff\x01\x00\x00tester', offset=0)

在Python2.7中,unpacked = (2, 511, 'tester'),这就是我想要的

在Python 3.6中,由于struct.unpack期望第二个参数为bytes,因此我尝试了以下方法:

import struct 

unpacked = struct.unpack('<BI6s', bytes('\x02\xff\x01\x00\x00tester', 'utf8'), offset=0)

unpacked = (2, 114627, b'\x00teste')

为什么我会得到一个不同的结果?我如何得到与2.7中相同的结果


Tags: 代码import参数bytesstructoffsettesterx00
1条回答
网友
1楼 · 发布于 2024-06-07 14:33:47

问题在于bytes()调用:

>>> bytes('\x02\xff\x01\x00\x00tester', 'utf8')
b'\x02\xc3\xbf\x01\x00\x00tester'

查看额外的字节\xc3\xbf?Python 3字符串是unicode,字符串中第二个字符(U+00FF)的UTF-8编码是0xC3 0xBF(请参见https://www.compart.com/en/unicode/U+00FF

解决方案是使用字节文字,其行为与Python 2相同:

unpacked = struct.unpack('<BI6s', b'\x02\xff\x01\x00\x00tester', offset=0)

相关问题 更多 >

    热门问题