简体   繁体   中英

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?

eg. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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