# 4 byte array to float conversion

Hello,

I’am working on a sketch where I receive 4 data bytes which I put in an array, now I want to convert this array of 4 bytes into a float value. Below is my code, the ??? is where the magic should be but unfortunately I have no clue as in how to tackle this problem.

Any help would be much appreciated

``````for(int i=0;i<=3;i++)
{
Serial.print(data,HEX); // prints the byte in hex

speedArray[i] = data; // uint8_t
}
Serial.println(""); // linefeed
speedFloat = ??? // SnelheidFloat
Serial.println(snelheidFloat);
``````

If we assume that the most significant byte is sent first, then you could do it this way:

``````long speedLong = 0;
byte speedArray[4];

for(int i = 0; i < 4; i++)
{
Serial.print(speedArray[i],HEX); // prints the byte in hex
speedLong = (speedLong << 8) | speedArray[i];
}
Serial.println(""); // linefeed
Serial.println(speedLong);
``````

If you don’t need to save the bytes in an array, you could use a single variable instead of speedArray inside your for loop.
Regards,
-Mike

Thanx Mike, I tried the conversion and it worked :), problem now is the number should have gone up slowly but it keeps jumping from negative to some positive number, I've looked up what the 4 byte data is supposed to mean but the explanation is in Delphi code:

I have looked up single and I think it is the Delphi equivelent of float so I changed to code but the same trick doesn't seem to work for float's.

``````DELPHI CODE!!!!
procedure ConvertSingle;
var
FOriginalSingle: Single;
FTransportArray: Array[0..3] of Byte;
FKopieSingle:    Single;

begin
// Init
FOriginalSingle := 1234.9876;
FKopieSingle    := 0.0;

// single to byte array
PSingle(@FTransportArray)^ := FOriginalSingle;

// Byte array decoding to single
FKopieSingle := PSingle(@FTransportArray)^;
end;
DELPHI CODE!!!!
``````

I have looked up single and I think it is the Delphi equivelent of float

It is.

Does this help... http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1207242838

The post you reffered to did help me find out that the byte order is normal (byte 4 is the last in the array and byte 1 the first). I can't really get to understand the union concept. I think I have to do the opposite of union as I have to combine 4 bytes to a float.

I think I must confess I replied to soon, I copied the code from the other page and by a miracle it worked right away (now that doesn't happen very often) :)

the code I used to convert is: In which snelheidArray[] are the bytes

``````float snelheid;

union u_tag {
byte b[4];
float fval;
} u;

u.b[0] = snelheidArray[0];
u.b[1] = snelheidArray[1];
u.b[2] = snelheidArray[2];
u.b[3] = snelheidArray[3];

snelheid = u.fval;
``````

Thanx for the help!!!, I can now use a computer trainsimulator game to send over the internet the speed the train is driving to an analogue 60 year old speedgauge using the Arduino MEGA and Ethernet Shield. Isn't life beautyful ;D

Isn't life beautyful

I agree!

I'm glad you got it working.