2's complement conversion. Is this right?
George Sakkis
george.sakkis at gmail.com
Sat Apr 19 20:10:30 EDT 2008
On Apr 18, 9:36 pm, Ross Ridge <rri... at caffeine.csclub.uwaterloo.ca>
wrote:
> Ross Ridge <rri... at caffeine.csclub.uwaterloo.ca> said:
>
> > If you have Python 2.5, here's a faster version:
>
> > from struct import *
> > unpack_i32be = Struct(">l").unpack
>
> > def from3Bytes_ross2(s):
> > return unpack_i32be(s + "\0")[0] >> 8
>
> Bob Greschke <b... at passcal.nmt.edu> wrote:
>
> > That's not even intelligible. I wanna go back to COBOL. :)
>
> It's the same as the previous version except that it "precompiles"
> the struct.unpack() format string. It works similar to the way Python
> handles regular expressions.
I didn't know about the Struct class; pretty neat. It's amazing that
this version without Psyco is as fast Bob's version with Psyco! Adding
Psyco to it though makes it *slower*, not faster. So here's how I'd
write it (if I wanted or had to stay in pure Python):
try: import psyco
except ImportError:
from struct import Struct
unpack_i32be = Struct(">l").unpack
def from3Bytes(s):
return unpack_i32be(s + "\0")[0] >> 8
else:
def from3Bytes(s):
Value = (ord(s[0])<<16) + (ord(s[1])<<8) + ord(s[2])
if Value >= 0x800000:
Value -= 0x1000000
return Value
psyco.bind(from3Bytes)
HTH,
George
More information about the Python-list
mailing list