packing hex value for socket.send
Jeff Epler
jepler at unpythonic.net
Wed Jul 14 09:11:58 EDT 2004
You can use the "hex" codec:
>>> "hello world".encode("hex")
'68656c6c6f20776f726c64'
>>> _.decode("hex")
'hello world'
If you want to convert a structure to/from hex, you can use something like
>>> struct.pack("f", 1.0).encode("hex")
'0000803f'
>>> struct.unpack("f", _.decode("hex"))
(1.0,)
or encapsulate them as functions:
def hexpack(*args):
return struct.pack(*args).encode("hex")
def hexunpack(f, s):
return struct.unpack(f, s.decode("hex"))
I'm not sure why you're dealing with arrays of length-2 strings in the
php code, but if you need to split a string like '68...64' into pairs of
chracters, you can use something like
def by_n(seq, n):
return [seq[i:i+n] for i in range(0, len(seq), n)]
>>> by_n("hello world".encode("hex"), 2)
['68', '65', '6c', '6c', '6f', '20', '77', '6f', '72', '6c', '64']
You can reverse this using str.join:
>>> "".join(_)
'68656c6c6f20776f726c64'
Good luck with your hex numbers.
Jeff
PS "_" is a special variable that refers to the last value printed in
the interactive interpreter, I used it above to make the examples
shorter.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040714/64aafaff/attachment.sig>
More information about the Python-list
mailing list