convert binary to float
Lie.1296 at gmail.com
Tue Jun 3 10:11:39 CEST 2008
On Jun 2, 2:55 am, Mason <john.gerald.ma... at gmail.com> wrote:
> I have tried and tried...
> I'd like to read in a binary file, convert it's 4 byte values into
> floats, and then save as a .txt file.
> This works from the command line (import struct);
> In : f = open("test2.pc0", "rb")
> In : tagData = f.read(4)
> In : tagData
> Out: '\x00\x00\xc0@'
> I can then do the following in order to convert it to a float:
> In : struct.unpack("f", "\x00\x00\xc0@")
> Out: (6.0,)
> But when I run the same code from my .py file:
> f = open("test2.pc0", "rb")
> tagData = f.read(4)
> print tagData
> I get this (ASCII??):
> I only know how to work with '\x00\x00\xc0@'.
> I don't understand why the output isn't the same. I need a solution
> that will allow me to convert my binary file into floats. Am I close?
> Can anyone point me in the right direction?
Did you know that '\x00\x00\xc0@' is Python's representation for the
'„@'. A print function calls str() first on what it's going to print,
and thus the binary representation is converted into real characters
(in the range of ASCII). If you've designed your code to process this
representation, then you should call the repr() first, a better
solution would be to design the code to process the binary directly,
python "knows" how to work with it, like if you do a for-loop, it
knows to fetch '\xc0' as one character instead of four.
More information about the Python-list