newbie sending hex values over UDP socket

Peter Hansen peter at engcorp.com
Tue Sep 14 22:34:09 CEST 2004


Bill Seitz wrote:

> OK, so I'm clear on sending a string.
> 
> If I want to send a numeric value, do I use something like
>   struct.pack('b',int)
> ?

I'd suggest playing a bit at the interactive prompt, watching
the results of everything you do.  For example, trying the
above with a few values would tell you exactly what it does,
provided you understand that you always see the *repr* value
for what is output there, rather than the item itself.  That
is, when your expression results in a string (as the above
does), you see the output of repr(s) instead of s itself,
and thus non-printing characters are escaped and the output
is surrounded by quotation marks:

 >>> import struct
 >>> struct.pack('b', 5)
'\x05'
 >>> struct.pack('b', 255)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
struct.error: byte format requires -128<=number<=127
 >>> struct.pack('b', -128)
'\x80'
 >>> struct.pack('b', 127)
'\x7f'
 >>> struct.pack('i', 127)
'\x7f\x00\x00\x00'
 >>> struct.pack('h', 127)
'\x7f\x00'
 >>> struct.pack('>h', 127)
'\x00\x7f'
 >>> struct.pack('<h', 127)
'\x7f\x00'

And things like that...  I think you'll be able to answer
most or all such questions yourself after that.

-Peter



More information about the Python-list mailing list