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: malc <malc@p...>
Subject: Re: How to read floats?
On Mon, 7 Aug 2000, Xavier Leroy wrote:

> > 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.
I overlooked this feature, very stupid, my appology.

> 
> 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 might come in handy too.

> 
> 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,
Sure, my ultra slow Caml function(crafted by a fellow low level coder)
will go away. Thanks!

> - Xavier Leroy
> 

-- 
mailto:malc@pulsesoft.com