Version française
Home     About     Download     Resources     Contact us    
Browse thread
How to read floats?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: How to read floats?
> I need to read binary data from files, C floats (32bit) in particular,
> maybe someone here already got code to do that? 

If your file contains a large array of 32-bit floats, the "map_file"
functions from the Bigarray module could do the job.

Otherwise, you could read the C float in a character string of length
4, then call the following C function to convert it into a
floating-point number:

  #include <caml/mlvalues.h>
  #include <caml/alloc.h>

  value extract_float(value s)
  {
    union { float f; char c[4]; } buffer;
    memcpy(buffer.c, String_val(s), 4);
    return copy_double(buffer.d);
  }

and its Caml declaration:

  external extract_float : string -> float = "extract_float"

This assumes the float in the file have the same endianness as the
processor.  If not, you'll need to reverse the string somewhere.

Hope this helps,

- Xavier Leroy