[MUD-Dev] Re: [CODE QUESTION] How to encode floats into bytes?

Richard Woolcock KaVir at dial.pipex.com
Mon Sep 7 19:09:38 CEST 1998


Ben Greear wrote:
> 
> On Mon, 7 Sep 1998, T. Alexander Popiel wrote:
> 
> > In message:  <Pine.LNX.3.96.980906215952.30075A-100000 at shamen.cyberhighway.net>
> >              Ben Greear <greear at cyberhighway.net> writes:
> > >
> > >What is the standard way (if there is one) to encode floating
> > >point numbers (double too I guess) into bytes for transport accross
> > >the network.
> > >
> > >I'm using c++, on both ends (encode/decode).
> > >
> > >It would seem like there would be a method to do this somewhere!
> >
> > Standard is to send raw IEEE format across the wire; just about
> > everyone uses IEEE internally these days, and those who don't
> > know how to convert, so they can talk with those that do.
> >
> > IEEE 32-bit format is bigendian: 1 sign bit, 8 bits exponent in
> > offset 127 notation, implied 1 (not stored), 23 bits mantissa.
> > Special codes are used in the exponent to denote NaN, +/-Inf,
> > and reduced-precision numbers between 2^-128 and 2^-152.
> >
> > IEEE 64-bit is similar, with 16 bits exponent and 47 bits
> > mantissa.
> >
> > If you do the conversion manually, actually check the standard;
> > I prolly have an off-by-one error in the above (which was taken
> > from memory).
> 
> I was looking at the standard last night..  You are at least
> very close :)  (Don't remember all the details myself.)
> 
> I'm going to play around with bit-masking and casting to see if
> I can get at the bits w/out turning the target into an integer!

How about

typedef union
{
   unsigned long Int;
   float         Float;
} int_float_type;

typedef union
{
   unsigned long Int[2];
   double        Double;
} int_double_type;

(copying the example from your other post)

   file_descriptor descriptor;  //assume it's connected appropriately.
   float           f_data = 42.5;
   int_float_type  if_data;
   if_data.Float = f_data;
   write(descriptor, if_data.Int, 0, 4);      //think those args are right..

And for doubles:

   file_descriptor descriptor;  //assume it's connected appropriately.
   double          d_data = 42.5;
   int_double_type id_data;
   id_data.Double = f_data;
   write(descriptor, if_data.Int[0], 0, 4);      //think those args are right..
   write(descriptor, if_data.Int[1], 0, 4);      //think those args are right..

Or maybe those last two lines could be replaced with:

   write(descriptor, if_data.Int, 0, 8);         //think those args are right..

Just a suggestion, don't know if it'll work though.

KaVir.




More information about the mud-dev-archive mailing list