2016-09-27 52 views
0

詳情: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 

爲什麼會發生這種情況,我如何獲得預期的輸出?

回答

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