简体   繁体   English

反转 Python Numpy 数组的位

[英]Reversing bits of Python Numpy Array

Suppose I have a numpy array of dtype uint16, how do I efficiently manipulate each element of the array so that the bits are reversed?假设我有一个 dtype uint16 的 numpy 数组,我如何有效地操作数组的每个元素以便反转位?

eg.例如。 0001111010011100 -> 0011100101111000 0001111010011100 -> 0011100101111000

The existing solutions on this website seem to suggest printing the number into a string which will be really slow for arrays.该网站上的现有解决方案似乎建议将数字打印到一个字符串中,这对于数组来说真的很慢。


Example of what I want to do:我想要做的例子:

test = np.array([128, 64, 32, 16, 8, 4, 2, 1]).astype(np.uint16)
out = reverse_bits(test)
print(out)
>> array([  256,   512,  1024,  2048,  4096,  8192, 16384, 32768], dtype=uint16)
arr = np.array(some_sequence)
reversed_arr = arr[::-1]

This will reverse bits in each element of an array.这将反转数组的每个元素中的位。

def reverse_bits(x):

    x = np.array(x)
    n_bits = x.dtype.itemsize * 8

    x_reversed = np.zeros_like(x)
    for i in range(n_bits):
        x_reversed = (x_reversed << 1) | x & 1
        x >>= 1
    return x_reversed

Here's one based off some old HAKMEM tricks.这是一个基于一些旧的 HAKMEM 技巧的。

def bitreverse16(x):
    x = ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8)
    x = ((x & 0x0F0F) << 4) | ((x & 0xF0F0) >> 4)
    x = ((x & 0x3333) << 2) | ((x & 0xCCCC) >> 2)
    x = ((x & 0x5555) << 1) | ((x & 0xAAAA) >> 1)
    return x

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

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