Mirror imaging binary numbers

dickinsm at gmail.com dickinsm at gmail.com
Wed Dec 6 19:32:04 EST 2006



On Dec 6, 7:20 pm, Grant Edwards <gra... at visi.com> wrote:
> It's a little less obtuse if you spell it this way:
>
> def flipbits(x):
>     """reverse bits in a byte"""
>     x1 = x << 4 | x >> 4
>     x2 = (x1 & 0x33) << 2 | (x1 & 0xcc) >> 2
>     return (x2 & 0x55) << 1 | (x2 & 0xaa) >> 1
>

Granted.  And a little more obtuse this way:

def flipbits(x):
    """reverse bits in a byte"""
    x += 255*(x & 15)
    x += 15*(x & 816)
    x += 3*(x & 5440)
    return x >> 7

I apologise---it's the end of a long day and I'm feeling more than a
little contrary.

Mark




More information about the Python-list mailing list