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

Ola Fosheim Grøstad <olag@ifi.uio.no> Ola Fosheim Grøstad <olag@ifi.uio.no>
Mon Sep 7 22:38:01 CEST 1998


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 :^)

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

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?
--
Ola Fosheim Groestad,Norway





More information about the mud-dev-archive mailing list