Mirror imaging binary numbers

Grant Edwards grante at visi.com
Wed Dec 6 18:15:23 EST 2006


On 2006-12-06, Craig <craigtw.online 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.

He's already told you 90% of the answer: use the bit operators
& | ~ ^ >> <<.

Here's the remaining 10% of the answer (done a couple different
ways):

def showbits8(b):
    mask = 0x80
    while mask:
        print "01"[(b & mask) != 0],
        mask >>= 1
    print
    
def bitswap8a(b):
    r = 0
    mask = 0x80
    while mask:
        r >>= 1
        if b & mask:
            r |= 0x80
        mask >>= 1
    return r

def bitswap8b(b):
    r = 0
    for m1,m2 in ((0x80,0x01),(0x40,0x02),(0x20,0x04),(0x10,0x08),(0x01,0x80),(0x02,0x40),(0x04,0x20),(0x08,0x10)):
        if b & m1:
            r |= m2
    return r


def testit(b):
    showbits8(b)
    showbits8(bitswap8a(b))
    showbits8(bitswap8b(b))
    print
    
testit(0xc1)
testit(0x55)
testit(0xe2)

        


-- 
Grant Edwards                   grante             Yow!  Is this "BOOZE"?
                                  at               
                               visi.com            



More information about the Python-list mailing list