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

Write hex code to text file from integer value in python

详细信息:Ubuntu14.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

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

如果你想要大端二进制数据,调用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