Reversing bits in a byte

88888 Dihedral dihedral88888 at googlemail.com
Tue Mar 12 12:00:51 EDT 2013


Oscar Benjamin於 2013年3月12日星期二UTC+8下午11時44分50秒寫道:
> 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

Now the dram is so cheap in the street. Please type in a tuple of 
all 8 bit inversions  from the index to the result then just take a look up
by the index to solve the problem. 

# there are ways to exchange the top 4 bits and the low 4bits, then swap
inside the nibbles then swap the 4 2bit pairs in the old way.



More information about the Python-list mailing list