Print an integer array as hexadecimal numbers

后端 未结 7 483
南方客
南方客 2020-12-11 00:43

I have an array created by using

array1 = np.array([[25,  160,   154, 233],
                   [61, 244,  198,  248],
                   [227, 226, 141, 72 ]         


        
相关标签:
7条回答
  • 2020-12-11 01:10

    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))})
    
    0 讨论(0)
  • 2020-12-11 01:12

    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
    
    0 讨论(0)
  • 2020-12-11 01:29

    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.

    0 讨论(0)
  • 2020-12-11 01:29

    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']]

    0 讨论(0)
  • 2020-12-11 01:30

    This one-liner should do the job:

    print '[' + '],\n['.join(','.join(hex(n) for n in ar) for ar in array1) + ']'
    
    0 讨论(0)
  • 2020-12-11 01:31
    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')
    
    0 讨论(0)
提交回复
热议问题