2's complement conversion. Is this right?

Ivan Illarionov ivan.illarionov at gmail.com
Mon Apr 21 17:30:04 EDT 2008


On 22 апр, 01:01, Peter Otten <__pete... at web.de> wrote:
> Ivan Illarionov wrote:
> > And even faster:
> > a = array.array('i', '\0' + '\0'.join((s[i:i+3] for i in xrange(0,
> > len(s), 3))))
> > if sys.byteorder == 'little':
> >     a.byteswap()
>
> > I think it's a fastest possible implementation in pure python
>
> Clever, but note that it doesn't work correctly for negative numbers. For
> those you'd have to prepend "\xff" instead of "\0".
>
> Peter

Thanks for correction.

Another step is needed:

a = array.array('i', '\0' + '\0'.join((s[i:i+3] for i in xrange(0,
len(s), 3))))
if sys.byteorder == 'little':
    a.byteswap()
result = [n if n < 0x800000 else n - 0x1000000 for n in a]

And it's still pretty fast :)



More information about the Python-list mailing list