Got a single octet from socket, what to do ?

Stephen Hansen apt.shansen at gmail.com
Fri Dec 4 21:47:55 EST 2009


On Fri, Dec 4, 2009 at 6:39 PM, mudit tuli <mudit.tuli at gmail.com> wrote:

> I am very new to Python and started getting to know socket programming
> recently.
> Made a socket server, which receives a "Single Octet"(treated as a single
> 8-bit integer field) from a client.
> But I am not sure what to do with this "Single Octet" and how to decode it
> into a long integer, so that I can make use of it .
> Any Ideas ?
>
>
Check out the "struct" module for low-level byte-stream protocols.

>>> my_byte = '\x0c'
>>> print struct.unpack("<B", my_byte)
(12, )

That would convert the byte string "my_byte" containing a single byte into a
tuple according to the format string passed.. In this case, < specifies
network/big-endian byte order, and "B" specifies that the the message
contains a single unsigned byte as a number. The tuple will thus contain a
12.

There's some other more direct ways you can approach the problem, but struct
is really IMHO best and using it early in your protocol is the best
practice.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091204/dbbb6553/attachment.html>


More information about the Python-list mailing list