473,394 Members | 1,843 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Reading a binary file

Hi all,

I am quite new to python and very new to this list.

I've got following problem. I have a binary file which contains
information I should read. I can open the file with

f = open ('cpu1db2.dat', 'rb')

That's no problem. But now I need the hex values of the binary file.

Is there a possibility to show hex-values of the bytes of a file?
Thanks in advance
Sorin
Jul 18 '05 #1
6 34663
Sorin Marti wrote:

I am quite new to python and very new to this list.

I've got following problem. I have a binary file which contains
information I should read. I can open the file with

[snip]

It would really be best if you could describe in more detail
what you are trying to do with this data. Bytes are bytes,
and things like hex and binary are just different _representations_
of bytes, so whether you want binary, hex, decimal, or something
else depends entirely on the use to which you will put the info.

-Peter
Jul 18 '05 #2
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
specifics.

-Peter
Jul 18 '05 #3
Am Thu, 26 Jun 2003 16:14:58 +0200 schrieb Sorin Marti:
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
----------------------------------------------------------------
[... content description ...]
So I have written a python class which makes a connection to the
[... lots of strange calculation ...]
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!


whew. I don't get it, but anyways I think I can be useful ;-)

look at the struct-module: "This module performs conversions between
Python values and C structs represented as Python strings. It uses format
strings (explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values. This can be
used in handling binary data stored in files or from network connections,
among other sources." (out of the python-doc).

learning by example:

to convert a 4 byte integer you'd write:
"struct.unpack("=I",str_of_len_4)[0]"

= means native endian format - use the machine's endian format
I means unsigned int
str_of_len_4 has to be a binary string of length 4 containing the int
and the [0] at the end is neccessary cause unpack *always* returns a list,
even if only one value is converted (otherwise it'd be [2387], for example).
this is even stackable:
"struct.unpack("=IIH", str_of_len_10)[0]"
converts two unsigned ints, one unsigned short. great, huh? :-)

Hope this is what you need. your explanations seemed rather complicated to
me ;-)
greetings,

axel.

Jul 18 '05 #4
Sorin Marti wrote:

Byte Number/Length Type Hex-Value
----------------------------------------------------------------
Byte 12,13,14,15,16: Real BB 42 C8 00 00

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!


I think you might be interpreting (or explaining?) the format of that
real incorrectly.

If the first bit is the sign, and the next 8 bits are the
exponent, and the rest is mantissa, then your exponent should
be 01110110 (or h76 or d118) and your mantissa value in hex
would be all of the 42 C8 00 00, or 1120403456 in decimal.

(Basically, your binary value as shown is wrong. BB42C80000 is really
1010 1010 0100 0010 1100 1000 0000 0000 0000 0000 0000 and not your
value of 0100 0010 1100 1000 0000 0000 0000 0000 as shown above.)

-Peter
Jul 18 '05 #5
look at the struct-module: "This module performs conversions between
Python values and C structs represented as Python strings. It uses format

to convert a 4 byte integer you'd write:
"struct.unpack("=I",str_of_len_4)[0]"

= means native endian format - use the machine's endian format
I means unsigned int
This is a drive-by post. I registered and stuff just to say thank you. :) The python struct docs aren't the greatest for someone like me who's never tried to read a binary file and convert endianness on the fly, and your post directed me to exactly what I needed to read to do it. :)

So thank you.
Aug 20 '05 #6
Hi, thanks for the "thank you"! :)

I just had some bad news, and one minute later I found that "thank you" mail of you. (A little late, I admit, but it served its purpose! :))
Oct 6 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: john smith | last post by:
Hi, I have a file format that is going to contain some parts in ascii, and some parts with raw binary data. Should I open this file with ios::bin or no? For example: filename: a.bin number of...
20
by: ishmael4 | last post by:
hello everyone! i have a problem with reading from binary file. i was googling and searching, but i just cant understand, why isnt this code working. i could use any help. here's the source code:...
6
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am...
50
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem...
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
30
by: siliconwafer | last post by:
Hi All, I want to know tht how can one Stop reading a file in C (e.g a Hex file)with no 'EOF'?
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
9
by: Use*n*x | last post by:
Hello, I have a binary file (image file) and am reading 4-bytes at a time. The File size is 63,480,320 bytes. My assumption is that if I loop through this file reading 4 bytes at a time, I...
3
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while...
6
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.