Search code examples
c++castingtype-conversionfloating-point-conversionuint8t

Convert a float to 4 uint8_t


I have got a float variable that I need to send through a CAN protocol. To do so, this float of 32 bits must be cut in 4 uint8_t variables.

I have absolutely no idea of how to do. I was first thinking of convert the float to an int but some answers that I found on the internet, which use cast or union doesn't seems to work.

Here's a simple example of what I am trying to do :

float f;
uint8_t ut1,ut2,ut3,ut4;

//8 first bits of f into ut1
//8 second bits of f in ut2
...

// Then I can send the uint8_t through CAN
...

Solution

  • You normally do this by casting the floatto an array ofuint8_t`.

    In C you can do it like this:

    uint8_t *array;
    array = (uint8_t*)(&f);
    

    In C++ it's better to use reinterpret_cast:

    uint8_t *array;
    array = reinterpret_cast<uint8_t*>(&f);
    

    Then array[0], ..., array[3] are your bytes.