Reading and manipulating binary data
Michael Peuser
mpeuser at web.de
Sat Aug 30 15:50:02 EDT 2003
"Dave" <davbucko at yahoo.com> schrieb im Newsbeitrag
news:biqh54$7sa$1 at balder.stud.idb.hist.no...
> Hi,
>
> I am really confused as to how to use binary data with python. I am
> currently developing a lightweight RADIUS server, which gets UDP datagrams
> from a client formatted like so:
>
> 0 1 2 3
> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
> | Code | Identifier | Length |
> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
> | |
> | Request Authenticator |
> | |
> | |
> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
> | Attributes ...
> +-+-+-+-+-+-+-+-+-+-+-+-+-
>
> I can read() the data easily enough from the socket. However, when I have
> read it, it is very difficult to manipulate. I can't convert it to an
> integer or a string which is driving me crazy... I have seen a lot of
posts
> recommending struct for dealing with binary data, but I can't get it to
like
> mine. I get all sorts of errors, like lengths don't match format etc.
I do not see the problem at the moment. You have got a string of binary data
(I think at least); the first 32 bit word consists of 2 bytes and a short.
Have a look at the following snippet:
from struct import *
x='\x01\x02\x00\xFF'
print unpack(">BBH",x)
This unpacks it quite easily. Note the '>'. I assume the length is
big-endian, if otherwise use '<' instead.
Kindly
Michael P
More information about the Python-list
mailing list