Mirror imaging binary numbers

dickinsm at gmail.com dickinsm at gmail.com
Wed Dec 6 18:45:54 EST 2006


On Dec 6, 6:01 pm, "Craig" <craigtw.onl... at gmail.com> wrote:
> Thanks so much for the response.  I have an array of individual bytes
> which will eventually make up a binary bitmap image that is loaded onto
> an LCD screen (1 = black dot, 0 = white dot).  At the moment each byte
> is reversed to what it should be (completely reverse the bit order):
> e.g 00111101 should be 10111100, 11001100 should be 00110011, etc.  It
> is not an int problem as such, it is more a bit level swap if you get
> what I mean.  If you could help that would be great.

Yet another solution:

def flipbits(x):
    """reverse bits in a byte"""
    x1 = x << 4 | x >> 4
    x2 = (x1 & 51) << 2 | (x1 & 204) >> 2
    return (x2 & 85) << 1 | (x2 & 170) >> 1

The idea is to first swap the two nybbles, then swap bits 0, 1, 5, 6
with 2, 3, 6, 7 respectively,
and finally swap bits 0, 2, 4, 6 with bits 1, 3, 5, 7 respectively.

Mark




More information about the Python-list mailing list