本机array.frombytes()(不是numpy!)神秘的行为

发布于 2025-01-19 16:24:34 字数 695 浏览 0 评论 0原文

[我不能使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-01-26 16:24:34

请注意,文档没有指定每种类型的确切大小,指定最小大小。这意味着如果需要的话,它可能会使用较大的尺寸,这可能是基于用于构建Python的C编译器中的类型。

这是我系统上的所有尺寸:

for c in 'bBuhHiIlLqQfd':
    print(c, array(c).itemsize)

b 1
B 1
u 2
h 2
H 2
i 4
I 4
l 4
L 4
q 8
Q 8
f 4
d 8

我建议使用'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:

for c in 'bBuhHiIlLqQfd':
    print(c, array(c).itemsize)

b 1
B 1
u 2
h 2
H 2
i 4
I 4
l 4
L 4
q 8
Q 8
f 4
d 8

I would suggest using the 'h' or 'H' type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文