1

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)
2
  • I'm curious, why do you need to do this? Commented Feb 4, 2020 at 23:21
  • I have an image mask saved as a 16bit tiff where the bits are coded to represent different classes. I just wanted a bijective way to visualise an image mask and "amplify" values with small differences.it wasn't strictly necessary as I am aware of alternatives. Commented Feb 5, 2020 at 2:38

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

This solves the problem but does not appear efficient. Other options may include packbits at least.
2

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

Comments

2

How about this version. I timed it about 6X faster than the bitreverse16 and 20X faster than the reverse_bits function for the given example vector.

def reverse_bits2(x):
    dtype = np.asanyarray(x).dtype
    return np.flip(np.packbits(np.flip(np.unpackbits(x.view(np.uint8)))).view(dtype))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.