# Transform 4 bytes into a float

Hello

I have 4 bytes that I read from a sensor: byte[0], byte[1], byte[2] and byte[3]. I have to put them in one single float.

I want to put the byte[0] in the first byte of the float, the byte[1] in the second one, the byte[2] in the third one and the byte[3] in the last one.

I believe that operators “<<” and “|” could help me but I am not sure and I don’t know how to use both of them.

If someone could attach me some code I really appreciate that.

Thanks!

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

union {
uint8_t b[4];
float f;
} data;

void loop() {
// put your main code here, to run repeatedly:
data.b[0]=0;
data.b[1]=1;
data.b[2]=2;
data.b[3]=3;
Serial.println(data.f);

}

You can also do this with a memcpy() operation.

byte data[4]; // read bytes in this array
float f; // the destination

memcpy(f, data, 4);

You can actually even read the bytes directly into the float:

float * f;
f[0] = readByte(); // The first byte of data.
f[1] = readByte(); // Second byte of data.

This you'd of course do in a for loop or so.

@OP

If you are sure that the discrete 4-byte data that you own are the components of a float number, then I would recommend to choose the advice of Post#1. Assume, float x = 14.53; byte[0] = 0xE1, byte[1] = 0x7A, byte[2] = 0x86, byet[3] = 0x41. (Serial.print((long)&x, HEX); //shows: 41687AE1)

data.b[0] = byte[0];
data.b[1] = byte[1];
data.b[2] = byte[2];
data.b[3] = byte[3];

Serial.print(data.f, 2);    //should show: 14.53

wvmarle:
You can actually even read the bytes directly into the float:

float * f;

f[0] = readByte(); // The first byte of data.
f[1] = readByte(); // Second byte of data.