Mirror imaging binary numbers
Grant Edwards
grante at visi.com
Wed Dec 6 19:20:36 EST 2006
On 2006-12-06, dickinsm at gmail.com <dickinsm at gmail.com> wrote:
> 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.
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
--
Grant Edwards grante Yow! Now I understand the
at meaning of "THE MOD SQUAD"!
visi.com
More information about the Python-list
mailing list