简体   繁体   English

Python:bytearray对象的长度与派生字节对象的长度不匹配吗?

[英]Python: The length of bytearray object does not match the length of derived bytes object?

Got some code like this: 得到了一些这样的代码:

some_buf = build_buffer() # returns a bytearray of ~40 bytes
align_buf(some_buf) # align it to 16 byte boundary
do_something(some_buf[16:32]) # This needs a bytes object, cannot work with bytearray

Alright, let me change it to this: 好吧,让我将其更改为:

some_buf = build_buffer() # returns a bytearray of ~40 bytes
align_buf(some_buf) # align it to 16 byte boundary
bytes_buf = bytes(some_buf)[16:32]
do_something(some_buf)

The do_something() complains the bytes object is not 16 byte aligned. do_something()抱怨bytes对象不是16字节对齐的。 To see what's going on, I added a simple condition: 为了查看发生了什么,我添加了一个简单的条件:

some_buf = build_buffer() # returns a bytearray of ~40 bytes
align_buf(some_buf) # align it to 16 byte boundary
bytes_buf = bytes(some_buf)[16:32]
if len(some_buf) != len(bytes_buf):
    msg = "Length of bytearray ({}) != Length of bytes object ({})".format(len(some_buf), len(bytes_buf))
    raise RuntimeError(msg)
do_something(some_buf)

And this is what I am getting: 这就是我得到的:

RuntimeError: Length of bytearray (144) != Length of bytes object (562)

I am on a Windows 10 x64 system, with Python ( CPython ) interpreter Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32 我在Windows 10 x64系统上,使用Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32上的Python( CPython )解释器Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32

Anyone else seen this behavior before? 其他人以前见过这种行为吗? If so, ideas/clues of what I might be missing here? 如果是这样,我可能在这里缺少什么的想法/线索?

FWIW, if this behavior is seen, and IntelHex module is in the control flow somewhere, it might be a bug. FWIW,如果看到此行为,并且IntelHex模块在控制流中的某个位置,则可能是错误。 Or at least, expect this unexpected behavior. 或者至少可以期待这种意外行为。 Somewhere in the conversion between Intel hex data to binary bytearray and from there to a bytes object, a blackhole probably exists. 某处二进制Intel十六进制数据之间的转换bytearray并从那里到一个bytes对象,黑洞可能存在。

In such cases, its probably worth trying with other versions or on other platforms (eg spin up a Linux VM) for the sake of cross-verification, at least. 在这种情况下,至少出于交叉验证的目的,可能值得在其他版本或其他平台(例如启动Linux VM)上进行尝试。

As mentioned in comments, this behavior was not observed with the same code paths on CPython '3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]' interpreter. 如评论中所述,在'3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]'上,使用相同的代码路径未观察到此行为口译员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM