Convert a float to 4 uint8_t

Evans Belloeil picture Evans Belloeil · Aug 19, 2014 · Viewed 25.6k times · Source

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
...

Answer

dohashi picture dohashi · Aug 19, 2014

You normally do this by casting the float to an array of uint8_t.

In C you can do it like this:

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

in C++ use the reinterpret_cast

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

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