Reading a binary file

Peter Hansen peter at
Thu Jun 26 17:15:50 CEST 2003

Sorin Marti wrote:
> Ok I'll try to give more details. I have a Siemens SPS. With an SPS you
> can controll machines such as pumps or motors or anything else. To
> controll you have to set Variables. If you want to see which state these
> variables have you can get a file via ftp where these values are stored.
> This is what I have done. Now I have a file (called cpu1db2.dat) and
> this file has a length of 16 bytes.
> Byte Number/Length   Type       Hex-Value
> ----------------------------------------------------------------
> Byte              1: Boolean:   01    (which is true, 00 would be false)
> Byte              2: Byte:      11   (This data type is called byte)
> Byte              3: Char:      50    (Which should be a "P")
> Byte            4,5: Word       00 00
> Byte            6,7: Integer    22 04
> Byte      8,9,10,11: DoubleWord D2 00 00 BB
> Byte 12,13,14,15,16: Real       BB 42 C8 00 00

Excellent detail!  (It's a pleasure to help someone who actually takes
the time to put together a question with this much care! Thank you. :-)

> Then there is a function where you can call a value with a startbyte and
> an endbyte. You also have to specify the type. That means you can call
> getValue('REAL',12,16) and you should get back 100 because if you have
> the binary value of 'BB 42 C8 00 00' is 01000010110010000000000000000000
> , first digit is the Sign (which is + or - ), next 8 digits are the
> exponent, in this case 10000101 = 133dec. Now you take away 127 from 133
> then you get six, thats the exponent. The rest
> (110010000000000000000000) has a hex value of C80000 this is 13107200
> decimal. Now you have to multiply 13107200 with 2^6 and 2^-23 and you
> get (tataaaaaa!): 100!
> The different data types need different calculations, that's why I asked
> a few things about changing the representation because I only can do
> some things in binary mode or hex mode.

Okay, so clearly you understand about bytes and such.... you just need
help with the specific ways of doing such things with Python. (?)

Folks have already shown you how to do hex(abyte) if you have a single
byte out of the above string of 16 bytes...  That will return a 
representation starting with 0x, however, so maybe ("%02x" % byte)
is more what you would need.  You can also extend that to ("%04x" % word)
or %08x for a long if you need.

More likely, the comments about using the struct module are right on
target.  You could easily write a string that would convert the entire
16 byte package all at once, except for your proprietary (?) float 
format, which you already have under control.

Check out struct, then if you still need help, we'll be down to 


More information about the Python-list mailing list