# Converting from bytes to float via Union not working on ESP32

**URL:** <https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182>\
**Category:** Programming\
**Created:** [March 14, 2022, 5:41pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182 "2022-03-14T17:41:56Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![michael\_st](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@michael\_st](https://forum.arduino.cc/u/michael_st)\
**Post date:** [March 14, 2022, 5:41pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/1 "2022-03-14T17:41:56Z")

</div>

I am trying to convert messages received on my CAN line into two separate floats (4 bytes) and then doing the same thing in the other direction to send. Converting from float to byte works but when I try to convert from bytes to floats the float is always 0.00. Below is the test code I am using. I am running this on the ESP32 dev kit v1

```cpp
typedef union {
    float value;
    byte bytes[sizeof(float)];
} FLOAT_BYTE_UNION;

FLOAT_BYTE_UNION test1;
FLOAT_BYTE_UNION test2;

void setup() {
  test1.value = 5;
  test2.bytes[0] = 0;
  test2.bytes[1] = 1;
  test2.bytes[2] = 2;
  test2.bytes[3] = 3;
  Serial.begin(115200);
  while (!Serial);
  
}

void loop() {
  Serial.println();
  for (int i = 0; i<sizeof(float); i++){
    Serial.print(test1.bytes[i], HEX);
  }
  Serial.print(" -> ");
  Serial.println(test2.value);
}

```

output is:

```cpp
00A040 -> 0.00

```

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [March 14, 2022, 5:45pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/2 "2022-03-14T17:45:35Z")

</div>

> [@michael\_st](#):
>
> ```arduino
> test1.value = 5;
> test2.bytes[0] = 0;
> test2.bytes[1] = 1;
> test2.bytes[2] = 2;
> test2.bytes[3] = 3;
> 
> ```

Tell us what you think is going-on there

---

<div class="post-metadata">

**Author:** ![michael\_st](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@michael\_st](https://forum.arduino.cc/u/michael_st)\
**Post date:** [March 14, 2022, 5:47pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/3 "2022-03-14T17:47:58Z")

</div>

Two separate tests. test1's float is being assigned to 5 and test2's bytes are being assigned to 0,1,2,3 respectively.

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [March 14, 2022, 5:49pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/4 "2022-03-14T17:49:43Z")

</div>

And what do you think is wrong with the results you are seeing?

(You're not really supposed to use unions for type-punning; use memcpy instead)

---

<div class="post-metadata">

**Author:** ![michael\_st](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@michael\_st](https://forum.arduino.cc/u/michael_st)\
**Post date:** [March 14, 2022, 5:50pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/5 "2022-03-14T17:50:53Z")

</div>

Byte array [0,1,2,3] should not equal 0.00 float correct?

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [March 14, 2022, 5:53pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/6 "2022-03-14T17:53:47Z")

</div>

Find yourself an IEEE754 converter online, and see what result it gives with those values.

---

<div class="post-metadata">

**Author:** ![michael\_st](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@michael\_st](https://forum.arduino.cc/u/michael_st)\
**Post date:** [March 14, 2022, 6:00pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/7 "2022-03-14T18:00:25Z")

</div>

Gotcha, it is a very small number. Thank you, I should have checked that before posting. I appreciate the help.

---

<div class="post-metadata">

**Author:** ![Perehama](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/perehama/32/256713_2.png) [@Perehama](https://forum.arduino.cc/u/Perehama)\
**Post date:** [March 14, 2022, 6:39pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/8 "2022-03-14T18:39:47Z")

</div>

When using a union to send bytes, between separate systems, one has to be aware of "Endian" problems. For example, AVR architecture like ATMega328P is little-endian while "Freescale" (NXP formerly Motorola) are notoriously Big-endian. I have no idea what a tensilica or whatever the esp32 is.

---

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [March 14, 2022, 6:45pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/9 "2022-03-14T18:45:52Z")

</div>

> [@Perehama](#):
>
> When using a union to send bytes

you should not use union for that in the first place 😉

---

<div class="post-metadata">

**Author:** ![wildbill](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/wildbill/32/1126438_2.png) [@wildbill](https://forum.arduino.cc/u/wildbill)\
**Post date:** [March 14, 2022, 6:51pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/10 "2022-03-14T18:51:01Z")

</div>

Your example code populates bytes in test1 but prints the value of test2.

---

<div class="post-metadata">

**Author:** ![Perehama](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/perehama/32/256713_2.png) [@Perehama](https://forum.arduino.cc/u/Perehama)\
**Post date:** [March 14, 2022, 6:52pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/11 "2022-03-14T18:52:05Z")

</div>

Agreed, but isn't that what the OP is doing? or do I missunderstand?

---

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [March 14, 2022, 6:55pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/12 "2022-03-14T18:55:50Z")

</div>

The way I understood it is that OP is receiving bytes on a CAN bus and wants to populate a structure with the data so s/he can then read multibytes data through the structure

the way to do this is to receive the data in a byte buffer and then use memcpy() to transfer the buffer into the struct (and let the compiler sort things out).

---

<div class="post-metadata">

**Author:** ![Perehama](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/perehama/32/256713_2.png) [@Perehama](https://forum.arduino.cc/u/Perehama)\
**Post date:** [March 14, 2022, 7:01pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/13 "2022-03-14T19:01:23Z")

</div>

Using a union to receive multiple bytes of a larger variable type is problematic for the same reasons as sending and receiving. The pitfall is endianness. Also, unions are implementation specific how the array is ordered with the float.

---

<div class="post-metadata">

**Author:** ![michael\_st](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@michael\_st](https://forum.arduino.cc/u/michael_st)\
**Post date:** [March 14, 2022, 7:04pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/14 "2022-03-14T19:04:24Z")

</div>

For reference this is my actual code. The original code was a test I was trying to preform.

```cpp
void CAN_Sender(void * parameters){
    FLOAT_BYTE_UNION translationMeasured_f;
    FLOAT_BYTE_UNION rotationMeasured_f;

    for(;;){
        double startTime = millis();
        translationMeasured_f.value = (float)Translation_Stepper.getCurrentPositionInMillimeters();
        rotationMeasured_f.value = (float)Rotation_Stepper.getCurrentPositionInRevolutions();;
        if (CAN_running()) {
            CAN.beginPacket(0b10010000 + (1 << boardID));
            for (int i = 0; i < sizeof(float); i++){
                CAN.write(translationMeasured_f.bytes[i]);
            }
            for (int i = 0; i < sizeof(float); i++){
                CAN.write(rotationMeasured_f.bytes[i]);
            }
            CAN.endPacket();
        }
        if (!RUNNING || !ENABLED) {
            CAN.beginPacket((1 << boardID) + 0b10000000);
            for (int i = 0; i < sizeof(float); i++){
                CAN.write(translationMeasured_f.bytes[i]);
            }
            for (int i = 0; i < sizeof(float); i++){
                CAN.write(rotationMeasured_f.bytes[i]);
            }
            CAN.endPacket();
        }
        double comExecutionTime = millis() - startTime;
        delay(COM_DELAY - comExecutionTime);
    }
}

//Need to decide on packet format
void CAN_Handler(int packet_size){
    FLOAT_BYTE_UNION translationDesired_f;
    FLOAT_BYTE_UNION rotationDesired_f;
    messageTime = millis();
    if (SERIAL_ON) {
        Serial.print("(packet: 0x");
        Serial.print(CAN.packetId(), HEX);
        Serial.print(" ");
    }

    //EMERGENCY STOP
    if (CAN.packetId() & 0b11110000 == 0b00000000) {
        SHUTDOWN();
        E_STOP = true;
        return;
    }

    //ZERO
    if (CAN.packetId() & 0b11000000 == 0b01000000) {
        SHUTDOWN();
        ZERO();
        START();
        return;
    }

    int rotationIndex = sizeof(float)-1;
    int translationIndex = sizeof(float)-1;
    bool dataReceived = false;
    while(CAN.available()){
        dataReceived = true;
        if (translationIndex >= 0){
            translationDesired_f.bytes[translationIndex--] = (byte)CAN.read();
        } else if (rotationIndex >= 0) {
            rotationDesired_f.bytes[rotationIndex--] = (byte)CAN.read();
        } else {
            if (SERIAL_ON) Serial.println("DATA DROPPED)");
            return;
        }
    }
    if (dataReceived){
        if (!((translationIndex < 0) && (rotationIndex < 0))) {
            if (SERIAL_ON) Serial.println("LESS THAN 8 BYTES RECEIVED)");
            return;
        }
        rotationDesired = (double)rotationDesired_f.value;
        translationDesired = (double)translationDesired_f.value;
        if (SERIAL_ON){
            Serial.print(" Rotation: ");
            Serial.print(rotationDesired);
            Serial.print(" Translation: ");
            Serial.print(translationDesired);
        }
    }

    if (SERIAL_ON) Serial.println(")");
    if (!RUNNING) START();
}

```

rotationDesired and translationDesired are doubles that are being using in another task to tell my stepper motors where to go. I have too many global variables here and need to do some clean up, but this shows generally what I am trying to do. I am doing everything in big endian.

---

<div class="post-metadata">

**Author:** ![westfw](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/westfw/32/213443_2.png) [@westfw](https://forum.arduino.cc/u/westfw)\
**Post date:** [March 14, 2022, 9:25pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/15 "2022-03-14T21:25:27Z")

</div>

> [@Perehama](#):
>
> AVR architecture like ATMega328P is little-endian while "Freescale" (NXP formerly Motorola) are notoriously Big-endian.

The Motorola 68k architecture was big-endian, but AFAIK all of their ARM Cortex chips are little-endian. The endianness of ARM (and also PPC and MIPS (eg PIC32) is actually selectable - sometimes when the chip is designed, sometimes at boot time via some pin state, and even at runtime (but not in Cortex-M, AFAIK.)

It's been a long time since I've seen a "new" chip that defaulted to big-endian.  
Tensilica (ESP8266, ESP32) and RISC-V are both little-endian.

> (You're not really supposed to use unions for type-punning; use memcpy instead)

Sigh. If you don't mind the significant performance hit. ☹

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [March 14, 2022, 9:39pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/16 "2022-03-14T21:39:49Z")

</div>

> [@westfw](#):
>
> Sigh. If you don't mind the significant performance hit.

Hey! I'm a native English speaker.  
I don't even agree it should refer to word-play, so please, don't shoot the messenger.

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [March 14, 2022, 10:41pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/17 "2022-03-14T22:41:02Z")

</div>

> [@westfw](#):
>
> Sigh. If you don't mind the significant performance hit. ☹

Which performance hit?  
`memcpy` is the correct way to do a cast like this. Compiler developers know that, and no sensible compiler will actually emit the call to `memcpy`. Especially if you're just inspecting the bytes of a float.

Proof: [Compiler Explorer](https://godbolt.org/z/azGes8hf1)

```cpp
float bytes_to_float(const unsigned char (&bytes)[4]) {
    float f;
    static_assert(sizeof f == sizeof bytes, "Unexpected float size");
    memcpy(&f, bytes, sizeof f);
    return f;
}

```

Is compiled into (GCC 11.2, ARM64, -O1):

```cpp
bytes_to_float(unsigned char const (&) [4]):
        ldr s0, [x0]
        ret

```

If you just use the resulting floats, they never even get instantiated. For example:

```cpp
// Interpret the two byte operands as floats, add them as floats, and store the
// result back into the first operand as a float.
void compound_add_floats_as_bytes(unsigned char (&op1)[4], unsigned char (&op2)[4]) {
    float op1_f, op2_f;
    static_assert(sizeof op1_f == sizeof op1, "Unexpected float size");
    memcpy(&op1_f, op1, sizeof op1_f);
    memcpy(&op2_f, op2, sizeof op2_f);
    float sum = op1_f + op2_f;
    memcpy(op1, &sum, sizeof sum);
}

```

```cpp
compound_add_floats_as_bytes(unsigned char (&) [4], unsigned char (&) [4]):
        ldr s0, [x0]
        ldr s1, [x1]
        fadd s0, s0, s1
        str s0, [x0]
        ret

```

---

<div class="post-metadata">

**Author:** ![westfw](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/westfw/32/213443_2.png) [@westfw](https://forum.arduino.cc/u/westfw)\
**Post date:** [March 14, 2022, 11:33pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/18 "2022-03-14T23:33:31Z")

</div>

> [@PieterP](#):
>
> Compiler developers know that, and no sensible compiler will actually emit the call to `memcpy`.

Are you willing to count on that?  
[Gcc 10.x for Cortex-M0](https://godbolt.org/z/oeGb5Enrj)

(I guess Cortex-M0 doesn't do unaligned accesses, so gcc punts and takes the easy way out. [clang does a little better.](https://godbolt.org/z/cEP4cjGh9) They both do better with CM3 or CM4.)  
(Hmm. MIPS and MSP430 both generate actual calls to memcpy() PPC and Tensilica have the alignment-fixign inline code like M0 clang)

---

<div class="post-metadata">

**Author:** ![6v6gt](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/6v6gt/32/225488_2.png) [@6v6gt](https://forum.arduino.cc/u/6v6gt)\
**Post date:** [March 14, 2022, 11:50pm UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/19 "2022-03-14T23:50:08Z")

</div>

> [@michael\_st](#):
>
> `if (CAN.packetId() & 0b11000000 == 0b01000000) {`

Be careful of operator priority. It is not what it should be.

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [March 15, 2022, 12:03am UTC](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182/20 "2022-03-15T00:03:51Z")

</div>

> [@westfw](#):
>
> I guess Cortex-M0 doesn't do unaligned accesses

You're probably not going to do this conversion without any context. In an artificial function like this, without knowing the alignment, performance is always going to suffer, but this is not the result of using `memcpy`, it's because the compilers cannot make the necessary assumptions to optimize the code effectively.

When the compiler has the necessary information, it optimizes it correctly:

```cpp
float bytes_to_float(const unsigned char (&bytes)[4]) {
    float f;
    static_assert(sizeof f == sizeof bytes, "Unexpected float size");
    memcpy(&f, std::assume_aligned<alignof f>(bytes), sizeof f);
    return f;
}

```

```cpp
bytes_to_float(unsigned char (&) [4]):
        ldr r0, [r0]
        bx lr

```

So if you compare the `memcpy` approach to the `union` approach in the same context (i.e. where alignment etc. is known), you'll see the same performance. But the former is valid, whereas the latter is not.

[Next page](https://forum.arduino.cc/t/converting-from-bytes-to-float-via-union-not-working-on-esp32/969182.md?page=2)
