[MLton-user] Raw conversion of 32 bits into Real32.t

Matthew Fluet fluet at tti-c.org
Mon Jan 22 09:32:21 PST 2007


> I have a 32-bit quantity and I want to get it at type Real32.t (as in
> the following C code).  Is there a way to do this in the mlton
> library?
> 
> union {
>   float f;
>   int32 i;
> } c;
> c.i = <some value>
> <now use c.f>
> 
> I want to do this in the context of unserialisation, so some
> equivalent way to achieve the same thing would be fine.

You can do it with the Basis Library via the PackWord<N> and PackReal<N> 
structures.  I'll assume you're on little endian intel hardware:

val convert =
   let
     val a = Word8Array.tabulate(4, fn _ => 0wx0)
   in
     fn (w: Word32.word) =>
       let
         val () = PackWord32Little.update (a, 0, w)
         val r = PackReal32Little.subArr (a, 0)
       in
         r
       end
   end





More information about the MLton-user mailing list