Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] read a float(double) in a file in a binary file
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Thorsten Ohl <ohl@p...>
Subject: [Caml-list] read a float(double) in a file in a binary file
polux moon <polux_moon@hotmail.com> writes:

> How can I read a float (double) in a binary format (output of a
> programe in c ) from a file ?

Here's what I use:

  (* This is hard coded value for Linux/Intel: *)
    let little_endian = true

    external float_of_bytes : string -> float = "float_of_bytes"

    let unsafe_rev8 s =
      let swap i1 i2 =
        let tmp = String.unsafe_get s i1 in
        String.unsafe_set s i1 (String.unsafe_get s i2);
        String.unsafe_set s i2 tmp in
      swap 0 7;
      swap 1 6;
      swap 2 5;
      swap 3 4

    let input_binary_float ic =
      let buf = String.create 8 in
      really_input ic buf 0 8;
      if little_endian then
        unsafe_rev8 buf;
      float_of_bytes buf

    let input_binary_floats ic array =
      let n = Array.length array in
      let bytes = 8 * n in
      let buf = String.create bytes in
      really_input ic buf 0 bytes;
      for i = 0 to n - 1 do
        let s = String.sub buf (8 * i) 8 in
        if little_endian then
          unsafe_rev8 s;
        array.(i) <- float_of_bytes s
      done

-- 
Thorsten Ohl, Physics Dept., Wuerzburg Univ. -- ohl@physik.uni-wuerzburg.de
http://theorie.physik.uni-wuerzburg.de/~ohl/     [<=== PGP public key here]
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners