text strings to binary...
John Machin
sjmachin at lexicon.net
Tue May 3 18:40:44 EDT 2005
On 3 May 2005 12:39:51 -0700, oriana.falco at thalesesec.com wrote:
>Hi,
>
>I've been working with Python for a bit now but I just came accross a
>problem and I'm not sure how to approach it. I'd like to convert a text
>string into binary data format. I though I'd use the struct module and
>the pack function but I can't get it to work.
"string to binary" tends to suggest "unpack", not "pack".
For example, you have read a 6-byte string from a file. You know that
it contains 3 x 2-byte unsigned integers in little-endian order.
>>> b6 = '\x01\x00\x00\x01\x02\x03'
>>> struct.unpack('<HHH', b6)
(1, 256, 770)
>>>
>From binary to string:
>>> struct.pack('<HHH', *(1, 256, 770))
'\x01\x00\x00\x01\x02\x03'
>>>
> I'm using Python 2.3.3 in
>Windows XP.
It's quite irrelevant to your question, but is there any good reason
why you're not using 2.4.1? If you *really* need to be on 2.3.x,
consider x == 5 -- that's 2 lots of bugfixes and IIRC a security patch
later than 2.3.3.
Cheers,
John
More information about the Python-list
mailing list