Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] how to split up a Caml float into its component bytes
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xleroy@p...>
Subject: Re: [Caml-list] how to split up a Caml float into its component bytes
> > I'm wondering how I would convert a floating point
> > number in OCaml (which I hope I am safe in assuming is IEEE-754) into
> > its equivalent bytes.
> 
> AFAIK, you have to write a C function.

Starting with OCaml 3.01, the Int64 module provides two functions
"bits_of_float" and "float_of_bits" which convert between floats and
an int64 matching the underlying 64-bit representation of the float.
>From the int64, extracting individual bytes is a simple matter of
shifting and masking.

> There is an undocumented primitive 
> 
>     external float_of_bytes : string -> float = "float_of_bytes"
> 
> defined in byterun/floats.c.  Unfortunately:
> 
>    a) the inverse is absent
>    b) on little endian machines one has to swap bytes.

a) is correct, b) is not (big endian representation is enforced).
Still, the functions from Int64 are less error-prone,
e.g. w.r.t. endianness.

- Xavier Leroy
-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr