Splitting a floating variable into 4 bytes?

Hey all,

I am working on a project where I need to split a floating variable into 4 bytes so I can transfer them over a rs485 setup.

I have been able to do this with int variables by using highByte and loByte; then I am able to reconstructing them using Value = word(loValue, hiValue);

Is there a function that can do this for a floating type that can split it into 4 variables?

Any help would be much appreciated. Thank you.

Andrew

Make a union of a float with byte [4];

Check out unions:
union unpack {
float f;
byte b[4];
}

Btw, there is no guarantee that the receiving equipment uses the same representation for floats. Even if they both use IEEE954, there could be endian issues.

As mentioned, endiness etc. might be a problem.
So is the size of the float. It's usually 4 bytes, but not always.
I would do something like this:

char *pf = reinterpret_cast<char*>(&float_variable);
for (byte i = 0; i != sizeof(float); ++i)
     send_byte(*pf++);

You could always send the "string" number, not the binary float number.

Except we don't know what is on the other end of the RS485, which - by implication - is some older bit of machinery that requires who knows what to function.

Hey all,

First, i wanted to say the receiving end is another Arduino Mega.

So after reading the responses and a tad more googling am i on the right track with the below code?

void loop()
{
  float temperature = 1.32324;
  temperaturebytebreakout(temperature);
}

void temperaturebytebreakout(float f) 
  {
  byte * b = (byte *) &f;
  temperature0 = (b[0]);
  temperature1 = (b[1]);
  temperature2 = (b[2]);
  temperature3 = (b[3]);
  }

Now for the receiving side I am really lost on how to proceed in order to put the float back together.

Thanks for all your help thus far.

Andrew

See reply #2 - use a union.

To send you put the float in and take out 4 bytes. To receive you put in 4 bytes and take out a float.

A union would be cleaner and more portable.

Thanks everyone! I think I may have it working.

Andrew

I was going to say that the union helps protect against alignment issues, but I don't think that is a problem for the Arduino.