Print an integer array as hexadecimal numbers

2020-02-06 05:02发布

问题:

I have an array created by using

array1 = np.array([[25,  160,   154, 233],
                   [61, 244,  198,  248],
                   [227, 226, 141, 72 ],
                   [190, 43,  42, 8]],np.int) ;

which displays as

[[25,  160, 154, 233]
 [61,  244, 198, 248]
 [227, 226, 141,  72]
 [190,  43,  42 ,  8]]

How do I display this array as hexadecimal numbers like this:

[[0x04,  0xe0,  0x48, 0x28]
 [0x66,  0xcb,  0xf8, 0x06]
 [0x81,  0x19,  0xd3, 0x26]
 [0xe5,  0x9a,  0x7a, 0x4c]]

Note: numbers in hex may not be real conversions of numbers in int. I have filled hex array just to give example of what I need.

回答1:

You can set the print options for numpy to do this.

import numpy as np
np.set_printoptions(formatter={'int':hex})
np.array([1,2,3,4,5])

gives

array([0x1L, 0x2L, 0x3L, 0x4L, 0x5L])

The L at the end is just because I am on a 64-bit platform and it is sending longs to the formatter. To fix this you can use

np.set_printoptions(formatter={'int':lambda x:hex(int(x))})


回答2:

Python has a built-in hex function for converting integers to their hex representation (a string). You can use numpy.vectorize to apply it over the elements of the multidimensional array.

>>> import numpy as np
>>> A = np.array([[1,2],[3,4]])
>>> vhex = np.vectorize(hex)
>>> vhex(A)
array([['0x1', '0x2'],
       ['0x3', '0x4']], 
      dtype='<U8')

There might be a built-in method of doing this with numpy which would be a better choice if speed is an issue.



回答3:

Just throwing in my two cents you could do this pretty simply using list comprehension if it's always a 2d array like that

a = [[1,2],[3,4]]
print [map(hex, l) for l in a]

which gives you [['0x1', '0x2'], ['0x3', '0x4']]



回答4:

This one-liner should do the job:

print '[' + '],\n['.join(','.join(hex(n) for n in ar) for ar in array1) + ']'


回答5:

If what you're looking for it's just for display you can do something like this:

>>> a = [6, 234, 8, 9, 10, 1234, 555, 98]
>>> print '\n'.join([hex(i) for i in a])
0x6
0xea
0x8
0x9
0xa
0x4d2
0x22b
0x62


回答6:

It should be possible to get the behavior you want with numpy.set_printoptions, using the formatter keyword arg. It takes a dictionary with a type specification (i.e. 'int') as key and a callable object returning the string to print. I'd insert code but my old version of numpy doesn't have the functionality yet. (ugh.)



回答7:

array1_hex = np.array([[hex(int(x)) for x in y] for y in array1])
print array1_hex
# => array([['0x19', '0xa0', '0x9a', '0xe9'],
#           ['0x3d', '0xf4', '0xc6', '0xf8'],
#           ['0xe3', '0xe2', '0x8d', '0x48'],
#           ['0xbe', '0x2b', '0x2a', '0x8']], 
#          dtype='|S4')