I am attempting to send a structure containing floating point data over a network, which comprises two different hardware architectures, written in C.
The client is running on x86_64 architecture, and the server is running on PPC (32bit) architecture.
It seems the only options I have for converting data to and from network friendly formats is:
htons
/ntohs
(2 byte) and htonl
/ntohl
(4 byte)
There appears to be no version which deals with floating point numbers (which makes sense, as differing architectures/endianness has different representations of floating point numbers).
So, I attempted splitting the floating point number into integer and exponent format in the following way:
void FtoME(float num, int32_t* mantissa, int32_t* exponent)
{
int32_t sig = (int32_t)num;
int32_t exp = 0;
double frac = num-sig;
double temp = num;
while (frac > 0 && exp > -20)
{
temp = temp * 10; //left shift the whole number
sig = (int32_t)temp; //get the integer part
frac = temp - sig; //get the fractional part
exp--;
}
printf("Scientific note: %dx10^%d\n",sig, exp);
*mantissa = sig;
*exponent = exp;
}
Now, whilst this does work in theory, in practice, I run into overflows a LOT, so clearly, this is not the correct way to handle this.
Are there other approaches I might try to be able to avoid overflows, and convert the float to a network friendly format (and importantly, back again), whilst not losing any data?