Need help with struct module

Gordon Scott gscott2112 at hotmail.com
Thu Oct 2 09:49:23 EDT 2003


Hi All,

I've got a problem I'm seeing when trying to use the struct module to send
data to a different machine.
Actually I'm making a condensed file that gets transferred to and read on a
BREW enabled cell-phone,
essentially I'm trying to format content as if it were being streamed over a
socket.

So I am trying to write a string by first sending a two-byte length of the
string followed by the string itself.
I noticed what looks to me like strange behavior in the struct module.

I am encoding the lengths of the strings by using socket.htons and then
packing them in a string as follows:

ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on
Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> import struct
>>> output = struct.pack('h', socket.htons(len('12345678')))
>>> output
'\x00\x08'
>>> output = struct.pack('h', socket.htons(len('123456789')))
>>> output
'\x00\t'
>>> output = struct.pack('h', socket.htons(len('1234567890')))
>>> output
'\x00\n'
>>> output = struct.pack('h', socket.htons(len('12345678901')))
>>> output
'\x00\x0b'
>>>

why in this example are the packing of 9 and 10 not showing '\x00\x09' and
'\x00\x0a' respectively?

On the target device when I read the file into a memory buffer and examine
the contents,
the value of 10 ('\x00\n') that I am expecting is litterally 00 0D and NOT
00 0A.   When I encode a longer string
in this maner such as length 12 or length 15, or shorter strings like length
7, everything works okay.

Any ideas?

PS. reversing the above steps in python correctlly returns 9 and 10.






More information about the Python-list mailing list