Write hex code to text file from integer value in python
Question: **Details: Ubuntu 14.04(LTS), Python(2.7)**

I want to write hex code to a text file so I wrote this code:

    
    
    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()
    

I expected like this:

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

But this is my actual result:

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

Why did this happen and how can I get my expected output?


Answer: If you want big endian binary data, call `astype(">i")` then `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()
    

If you want hex text:

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

the output:

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

