简体   繁体   English

Numpy 将数组中的一系列整数转换为十六进制值

[英]Numpy to convert series of integers in array to hex value

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.我有一个图像数组,我使用 Numpy 将其转换为 16 x 1000000 的 4 个值数组,其中每个值都是 2 位整数。 Shown below is a small part of an array.下面显示的是数组的一小部分。 I need to convert each column to a hexadecimal word in this format(0x00000000).我需要将每一列转换为这种格式的十六进制单词(0x00000000)。 The first column would be ??3022133203023123 or (0xCA7E32DB).第一列是 ??3022133203023123 或 (0xCA7E32DB)。 All values formatted to 8 digits.所有值都格式化为 8 位数字。 I tried it using for statements without numpy and it was too slow.我尝试使用 for 没有 numpy 的语句,但它太慢了。

    [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?如何使用 numpy 功能处理上述内容? 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.我想采用 16 x 1000000 矩阵并获得 4000000 个十六进制值或 1000000 组 4 个十六进制值的矩阵。

I found my solution.我找到了我的解决方案。 Using np.arange(...) is literally a numpy direct replacement of a (for) loop that generates a matrix.使用 np.arange(...) 实际上是对生成矩阵的 (for) 循环的 numpy 直接替换。 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.如果需要,我还可以使用 np.set_printoptions 来获取十六进制格式。

b = np.arange(0,160).reshape(16,10)
r = ((4** np.arange(16)[::-1])) #
print(r.dot(b[:, np.arange(10)]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM