Mirror imaging binary numbers
Hendrik van Rooyen
mail at microcorp.co.za
Thu Dec 7 01:57:53 EST 2006
"Craig" <craigtw.online at gmail.com> wrote:
> Hi there,
>
> I'm trying to switch binary numbers around so that the MSB becomes the
> LSB etc. Is there an easy way of doing this as I can't seem to find
> anything. If you could help that would be great. Thanks and good
> luck.
Are these Python ints, or are they "strings of bytes of known length"?
And do you really want to mirror swap the binary bits or just change the
byte sequence from say big to little endian?
- i.e. is MSB most significant bit, or byte?
assuming bit, try this:
>>> num = 12345
>>> q,r = divmod(num,2)
>>> q
6172
>>> r
1
>>> l = [r]
>>> while q:
q,r = divmod(q,2)
l.append(r)
>>> l
[1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1]
>>> ans = 0
>>> for x in l:
ans = ans * 2 + x
>>> ans
9987
>>>
and Robert is yer aunty...
- Hendrik
More information about the Python-list
mailing list