在python中将十六进制代码写入文本文件中的整数值

时间:2016-09-27 13:26:04

标签: python-2.7 numpy integer hex ubuntu-14.04

详情:Ubuntu 14.04(LTS),Python(2.7)

我想将十六进制代码写入文本文件,所以我编写了这段代码:

import numpy as np

width = 28    
height = 28
num = 10

info = np.array([num, width, height]).reshape(1,3)
info = info.astype(np.int32)

newfile = open('test.txt', 'w')
newfile.write(info)
newfile.close()

我期待这样:

00 00 00 0A 00 00 00 1C 00 00 00 1C

但这是我的实际结果:

0A 00 00 00 1C 00 00 00 1C 00 00 00

为什么会发生这种情况?如何获得预期的输出?

1 个答案:

答案 0 :(得分:2)

如果您需要大端二进制数据,请致电astype(">i"),然后致电tostring()

import numpy as np

width = 28    
height = 28
num = 10

info = np.array([num, width, height]).reshape(1,3)
info = info.astype(np.int32)
info.astype(">i").tostring()

如果你想要十六进制文字:

" ".join("{:02X}".format(x) for x in info.astype(">i").tostring())

输出:

00 00 00 0A 00 00 00 1C 00 00 00 1C