What is the best method for reading a double from a binary created in C?

Program C spits out sequential doubles to a binary file. I want to read them in Python. I tried to usestruct.unpack('d',f.read(8))

EDIT: I used the following in C to write a random double number

r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);

Errors are now fixed, but I can not read the first value. for the whole number 0.000 .. he reads it as 3.90798504668055, but everything else is in order.

+5
source share
5 answers

, , . , "3.907985046680551e-14" - (0.000000000000039 ). , C- , python.

[Edit] C, ( : 3.90799e-14) ( printf ( "% g", val)), , , .

+3

" "? ? ? ?

:

  • ,

:

  • , , ? big-endian, - little-endian, endianness .

  • , ? ? , , , ?

+1

-, pickle? Python... python:

import Numeric as N
import array
filename = "tmp.bin"
file = open(filename, mode='rb')
binvalues = array.array('f')
binvalues.read(file, num_lon * num_lat) 
data = N.array(binvalues, typecode=N.Float)   

file.close()

, 4 . .

- :

   tmp=[]
   for line in open("data.dat"):
                tmp.append(float(line))
+1
  • f.read(8) 8
  • / endianness:

    >>> for c in '@=<>':
    ...     print repr(struct.pack(c+'d', -1.05))
    ...
    '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
    '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
    '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
    '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd'
    >>> struct.unpack('<d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd')
    (-6.0659880001157799e+066,)
    >>> struct.unpack('>d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd')
    (-1.05,)
    
0

- ASCII:

0,0
3.1416
3.90798504668055

, .

double ​​ .

, , C, , .

, ifs/ifdefs, , double, , Python.

Writing such code would be difficult, so I offer an easy, clean, portable, and user-friendly ASCII text solution.

This will be my definition of "best."

0
source

All Articles