type converion in python

Steven Taschuk staschuk at telusplanet.net
Wed May 28 22:39:31 EDT 2003


Quoth Ulrich Petri:
  [...]
> # i'm assuming buf is buffer with data
> #i dont know how much bytes a uint2 has....
> bytes_per_uint = 2
> 
> list_of_ints = [int(buf[i:i+bytes_per_uint]) for i in
> xrange(len(buf)/bytes_per_uint)]

The OP doesn't need '1234' -> 1234, which is what int() does; he
needs '\x12\x34' -> 0x1234 or something similar.  For that the
struct module is probably most convenient, as Peter said.

(That said, you *could* use int() if you were really enthusiastic
about it:
    >>> int(''.join(['%02x' % ord(c) for c in '\x12\x34']), 16)
    4660
or
    >>> import binascii
    >>> int(binascii.hexlify('\x12\x34'), 16)
    4660
But I'm not sure why you'd want to, given that the struct module
exists.)

-- 
Steven Taschuk                  staschuk at telusplanet.net
"Telekinesis would be worth patenting."  -- James Gleick





More information about the Python-list mailing list