Reversing bits in a byte

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 12 11:44:50 EDT 2013


On 12 March 2013 14:59, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> Numpy and matplotlib will do what you want:
>
> import numpy as np
> import matplotlib.pyplot as plt
>
> def bits_to_ndarray(bits, shape):
>     abytes = np.frombuffer(bits, dtype=np.uint8)
>     abits = np.zeros(8 * len(abytes), np.uint8)
>     for n in range(8):
>         abits[n::8] = (abytes % (2 ** (n+1))) != 0

Whoops! The line above should be
        abits[n::8] = (abytes & (2 ** n)) != 0

>     return abits.reshape(shape)
>
> # 8x8 image = 64 bits bytes object
> bits = b'\x00\xff' * 4
>
> img = bits_to_ndarray(bits, shape=(8, 8))
> plt.imshow(img)
> plt.show()
>
>
> Oscar



More information about the Python-list mailing list