本机array.frombytes()(不是numpy!)神秘的行为
[我不能使用numpy,所以请不要谈论它]
i(显然是天真的)以为python array.frombytes()
将从代表各种机器格式的一系列字节中读取整数,取决于您的创建 array
对象的方式。在创建时,您需要提供一个字母类型代码,告诉它(或我认为)机器类型的整数组成了字节流。
import array
b = b"\x01\x00\x02\x00\x03\x00\x04\x00"
a = array.array('i') #signed int (2 bytes)
a.frombytes(b)
print(a)
array('i', [131073, 262147])
and in the debugger:
array('i', [131073, 262147])
itemsize: 4
typecode: 'i'
b
中的字节是一系列的小ENDIAN int16s (类型code ='i')。尽管被告知,它将字节解释为4字节整数。这是Python 3.7.8。
我确实需要将变化的ints转换为python int的数组(或列表),以处理字节流中的图像数据,但实际上是16位或32位整数,或64位双浮动格式。我想念或做错了什么?还是完成此操作的正确方法是什么?
[I cannot use numpy so please refrain from talking about it]
I (apparently naively) thought Python array.frombytes()
would read from a series of bytes representing various machine format integers, depending on how you create the array
object. On creation you are required to provide a letter type code telling it (or so I thought) the machine type of integer making up the byte stream.
import array
b = b"\x01\x00\x02\x00\x03\x00\x04\x00"
a = array.array('i') #signed int (2 bytes)
a.frombytes(b)
print(a)
array('i', [131073, 262147])
and in the debugger:
array('i', [131073, 262147])
itemsize: 4
typecode: 'i'
The bytes in b
are a series of little endian int16s (type code = 'i'). Despite being told this, it interpreted the bytes as 4-byte integers. This is Python 3.7.8.
I really need to convert the varying ints into an array (or list) of Python ints to deal with image data coming in byte-streams but which is actually either 16-bit or 32-bit integer, or 64 bit double floating format. What did I miss or do wrong? Or what is the right way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,文档没有指定每种类型的确切大小,指定最小大小。这意味着如果需要的话,它可能会使用较大的尺寸,这可能是基于用于构建Python的C编译器中的类型。
这是我系统上的所有尺寸:
我建议使用
'H'
或'H'
类型。Note that the documentation doesn't specify the exact size of each type, it specifies the minimum size. Which means it may use a larger size if it wants, probably based on the types in the C compiler that was used to build Python.
Here are all the sizes on my system:
I would suggest using the
'h'
or'H'
type.