I am writing a C program that communicates over modbus TCP. I send the float 3.14
on my modbus client, with a hexadecimal representation of 0x4048F5C3
. My C code is correctly receiving the modbus packet, and now I just need to reinterpret the unsigned char *buffer
as a float so I can get the value 3.14
. Here is my code
int main()
{
setup_modbus_tcp();
unsigned char buffer[4] = { 0x00, 0x00, 0x00, 0x00 };
get_modbus_data(buffer, 4);
//Buffer now holds { 0x40, 0x48, 0xF5, 0xC3 };
float value = *(float *)buffer;
//value is now -490.564453
}
Now, I can tell that this problem is because of endianness, because if I swap endianness so that the buffer looks like this:
{ 0xC3, 0xF5, 0x48, 0x40 };
then everything works fine. But this feels a little bit messy. Do I have to swap endianness? Or is there a way that I can specify endianness when I do:
float value = *(float *)buffer;