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: malc <malc@p...>
Subject: Re: [Caml-list] how to split up a Caml float into its component bytes
On Fri, 9 Nov 2001, Rafael 'Dido' Sevilla wrote:

> 
> I've been writing a byte compiler for a small language using Objective
> Caml, and now am thinking about incorporating floating point support
> into the language.  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.  I need it to be able to output bytecode
> instructions that will load floating point constants into the virtual
> machine.  In C this is fairly trivial to do; not sure how to do it in
> OCaml.

This code is for single precission floats.

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

/* Kindly suggested by Xavier Leroy on Caml Mailing List */
value unpack_float (value s)
{
  union { float f; char c[4]; } buffer;
  memcpy (buffer.c, String_val (s), 4);
  return copy_double ((double) buffer.f);
}

value pack_float (value d)
{
  value s;
  union { float f; char c[4]; } buffer;

  s = alloc_string (4);
  buffer.f = (float) Double_val (d);
  memcpy (String_val (s), buffer.c, 4);
  return s;
}

module Fltstub = struct
  external pack : float -> string = "pack_float"
  external unpack : string -> float = "unpack_float"
end

-- 
mailto:malc@pulsesoft.com

-------------------
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