Skip to main content
Associate
Oct 29, 2025 12:16 PM UTC
Question

Split data from a float array into an uint8_t array

Hi,

I just stumbled upon something interesting (at least for me). For my current project I need to store data from a float array with two elements in an uint8_t array with eight elements. I use the following code to archive this:

pnt = (uint8_t*)out;
for(i = 0; i < 8; i++)
{
 uart_tx_buffer[i + 3] = *(pnt + i);
}

While it technically works, the bytes from each float element get stored in the buffer in a reversed order. I can give you an example from what I am looking at in the debug session. The float array has the values out = {0x41bef708, 0x4478a1d7}. So the result I exacted for the buffer is uart_tx_buffer = {xx, xx, xx, 0x41, 0xbe, 0xf7, 0x08, 0x44, 0x78, 0xa1, 0xd7}. But in reality it looks like this uart_tx_buffer = {xx, xx, xx, 0x08, 0xf7, 0xbe, 0x41, 0xd7, 0xa1, 0x78, 0x44}.

At first I thought the values in the buffer are completely random because I made a mistake. It took me a while to figure this out. What is the reason why this happens? Can I avoid this, because now I would have to shift all these bytes around.

I am using STM32CubeIDE 1.19.0 to program a NUCLEO-F429ZI.

This topic has been closed for replies.

2 replies

Ozone
Principal
Oct 29, 2025 12:45 PM UTC

This issue is called endianness, and refers to an architecture's way of storing and accessing objects greater than 1 byte (usually the minimal size for an object in memory).
https://en.wikipedia.org/wiki/Endianness
If it comes to communication between different systems, either use ASCII/text format, or stick to one endianness. 
As an example, CANopen defines "Little Endian" for all message transfers.

TDK
Oct 29, 2025 12:52 PM UTC

If you want the same memory order, use memcpy.

uint8_t one[8];
float two[2];
memcpy(two, one, 8);

If byte order needs swapped, you can use __REV to reverse endianness: 

uint8_t one[8];
float two[2];
two[0] = __REV(((uint32_t*)one)[0]);
two[1] = __REV(((uint32_t*)one)[1]);

 

"If you feel a post has answered your question, please click ""Accept as Solution""."