Numpy to convert series of integers in array to hex value

0

I have an image array where I use Numpy to convert it to a 16 x 1000000 array of 4 values where each value is a 2 bit integer. Shown below is a small part of an array. I need to convert each column to a hexadecimal word in this format(0x00000000). The first column would be ??3022133203023123 or (0xCA7E32DB). All values formatted to 8 digits. I tried it using for statements without numpy and it was too slow.

    [3 3 1 1],[0 2 3 0],[1 2 2 0],[1 0 3 0],[3 0 3 2]...
    [0 0 3 3],[0 3 1 0],[1 3 0 0],[0 2 3 2],[1 2 2 0]...
    [2 3 0 2],[0 3 2 2],[0 2 1 2],[0 0 0 3],[2 0 2 3]...
    [2 1 3 1],[1 2 1 0],[3 2 0 3],[2 2 0 2],[1 1 0 3]...
    [1 0 2 1],[2 1 3 2],[2 1 0 2],[3 0 1 0],[3 0 2 2]...
    [3 3 1 0],[2 3 2 1],[0 0 3 0],[3 1 1 0],[2 0 1 0]...
    [3 1 0 3],[0 3 3 1],[1 1 1 2],[2 1 2 1],[3 2 2 1]...
    [2 1 1 0],[3 1 3 3],[2 3 1 0],[0 1 3 1],[1 3 0 2]...
    [0 2 1 1],[1 1 1 0],[2 0 0 3],[1 0 0 3],[2 3 3 1]...
    [3 1 0 0],[3 3 2 0],[3 3 0 0],[3 3 3 3],[1 3 2 1]...
    [0 3 3 3],[2 0 3 2],[3 3 0 2],[1 1 1 0],[3 3 1 2]...
    [2 2 2 1],[0 0 0 1],[3 2 0 3],[2 1 0 1],[0 3 3 1]...
    [3 1 3 0],[2 1 1 2],[1 1 2 3],[3 3 1 3],[2 2 0 1]...
    [1 0 2 0],[2 3 3 1],[2 2 3 2],[1 0 0 1],[3 0 2 2]...
    [2 1 1 3],[2 3 1 3],[1 3 1 2],[0 3 2 3],[0 0 2 3]...
    [3 3 2 1],[2 1 1 3],[3 2 3 3],[2 0 1 0],[1 1 0 0]...

I have tried something like

a5 = (hex(a2.dot(1 << np.arange(16)[::-1])))

But even with this, I could only get it to work on a simple 1D matrix and it returned an integer.

How can I process the above using a numpy feature? I would like to take the 16 x 1000000 matrix and get a matrix of 4000000 hex values or 1000000 sets of 4 hex values.

python
arrays
numpy
asked on Stack Overflow Nov 19, 2020 by DougP

1 Answer

0

I found my solution. Using np.arange(...) is literally a numpy direct replacement of a (for) loop that generates a matrix. I am using it to sum over indices. Here is an example. I can also use np.set_printoptions to get hex format if needed.

b = np.arange(0,160).reshape(16,10)
r = ((4** np.arange(16)[::-1])) #
print(r.dot(b[:, np.arange(10)]))
answered on Stack Overflow Nov 19, 2020 by DougP

User contributions licensed under CC BY-SA 3.0