在python中将整数转换为大端字节二进制文件 [英] Convert integer to big endian binary file in python

查看:330
本文介绍了在python中将整数转换为大端字节二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Python将由整数组成的2D数组转换为大端字节二进制文件:

I'm trying to convert a 2D-array composed by integers to a big endian binary file using Python by this way:

import struct;

fh=open('file.bin','wb')
for i in range(width):
    for j in range(height):
        fh.write(struct.pack('>i2',data[i,j]))

fh.close()

当我用numpy打开它时:

when I open it with numpy:

a=np.fromfile('file.bin',dtype='>i2')

结果是一个数组原始数据之间的零:

The result is an array with zeros between original data:

[266,   0, 267,   0, 268,
   0, 272,   0, 268,   0, 264,   0, 266,   0, 264,   0, 263,   0,
 263,   0, 267,   0, 263,   0, 265,   0, 266,   0, 266,   0, 267,
   0, 267,   0, 266,   0, 265,   0, 270,   0, 270,   0, 270,   0,
 272,   0, 273,   0, 275,   0, 274,   0, 275]

这就是我要获得的:

[266,   267,  268,  272,  268,   264,  266,  264,  263, 
 263,   267,  263,  265,  266,   266,  267,
 267,   266,  265,  270,  270,   270,  272,  273,  275,  274,  275]

您知道我的代码有什么问题吗?

Do you know what is wrong with my code?

推荐答案

i2 替换为 I2 对我有用。

a = np.fromfile('file.bin',dtype='>I2')

然后, np.fromfile 行为似乎很奇怪(它说> i2 是int16,但是当您明确说 np.int16 时,它会输出其他内容。

Then again, the np.fromfile behaviour seems weird (it says >i2 is int16, but when you explicitly say np.int16 it outputs something else).

In [63]: np.fromfile('npfile.bin',dtype='>i2')
Out[63]: array([  0, 345,   0, 245,   0, 345,   0, 245], dtype=int16)

In [64]: np.fromfile('npfile.bin',dtype=np.int32)
Out[64]: array([1493237760, -184549376, 1493237760, -184549376], dtype=int32)

In [65]: np.fromfile('npfile.bin',dtype=np.uint32)
Out[65]: array([1493237760, 4110417920, 1493237760, 4110417920], dtype=uint32)

In [66]: np.fromfile('npfile.bin',dtype=np.int16)
Out[66]: array([    0, 22785,     0, -2816,     0, 22785,     0, -2816], dtype=int16)

这篇关于在python中将整数转换为大端字节二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆