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

Ben Greear greear at cyberhighway.net
Mon Sep 7 14:39:11 CEST 1998


On Mon, 7 Sep 1998, Ola Fosheim Grxstad wrote:

> Ben Greear wrote:
> > 
> > 
> > Maybe I'm being too complicated. Maybe something like this would encode:
> 
> Yeah.
> 
> > file_descriptor f;  //assume it's connected appropriately.
> > float f = 42.5;
> > char* bytes = (char*)(&f);
> > write(f, bytes, 0, 4);      //think those args are right..
> > 
> > This ignores network order, but I can deal with that.
> 
> (but your compiler can't deal with multiple f variables :^)

Stupid compilers! :)

> 
> typedef unsigned long uint32;
> typedef unsigned char uint8;
> assert(sizeof(float)==4);
> assert(sizeof(uint32)==4);
> assert(char is 8 bit);

> assert(floats use same endianess as ints);

I can't figure this one out.  Probably end up doing something
silly like just testing it between my pc and a sun station.  Nothing
in the standards, that I have seen, mention endian-ness.  And there
is nothing resembling ntohl for floats.

Of course, with the code below, I can covert the floats to ints and
then do the ntohl/htonl conversion....  Have to look for more
details...


> 
> void conv(const float f,uint8 *dst){
> 	const uint32 i = *((uint32 *)(void *)&f);
> 	dst[0] = (uint8)((i>>24)&0xff);
> 	dst[1] = (uint8)((i>>16)&0xff);
> 	dst[2] = (uint8)((i>>8)&0xff);
> 	dst[3] = (uint8)((i)&0xff);
> }
> 
> Does Java provide functions for converting floats to raw bytes?

Yes.  Look in the Double and Float classes:

This is from the JavaDocs for the JDK.

Float.floatToIntBits() 

 public static native int floatToIntBits(float value)

      Returns the bit represention of a single-float value. The result is
a representation of the floating-point argument according to
      the IEEE 754 floating-point "single precision" bit layout. 

      Bit 31 represents the sign of the floating-point number. Bits 30-23
represent the exponent. Bits 22-0 represent the
      significand (sometimes called the mantissa) of the floating-point
number. 

      If the argument is positive infinity, the result is 0x7f800000. 

      If the argument is negative infinity, the result is 0xff800000. 

      If the argument is NaN, the result is 0x7fc00000. 

      Parameters: 
            value - a floating-point number. 
      Returns: 
            the bits that represent the floating-point number. 

> --
> Ola Fosheim Groestad,Norway
> 
> 
> -- 
> MUD-Dev: Advancing an unrealised future.
> 


Ben Greear (greear at cyberhighway.net)  http://www.primenet.com/~greear 
Author of ScryMUD:  mud.primenet.com 4444
http://www.primenet.com/~greear/ScryMUD/scry.html






More information about the mud-dev-archive mailing list