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
我正在编写一个通过modbus TCP进行通信的C程序。我在我的modbus客户端发送浮点数3.14,十六进制表示为0x4048F5C3。我的C代码正确接收modbus数据包,现在我只需要将unsigned char * buffer重新解释为float,这样我就可以得到值3.14。这是我的代码
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;
1 个解决方案
#1
2
The buffer must be handled manually, this includes changes to endianness. A function can always be used that converts the buffer to a floating point format.
必须手动处理缓冲区,这包括对字节序的更改。始终可以使用将缓冲区转换为浮点格式的函数。
float value = Convert( buffer );
To add, you way of converting the buffer is incorrect:
要添加,您转换缓冲区的方式不正确:
float value = *(float *)buffer;
An array of unsigned chars cannot be simply to a float
type, as it causes undefined behavior. The memory must be copied to an object of type float
:
无符号字符数组不能简单地为float类型,因为它会导致未定义的行为。必须将内存复制到float类型的对象:
float value;
memcpy( &value , buffer , sizeof( value ) ); //assumes endianness has already been handled
#1
2
The buffer must be handled manually, this includes changes to endianness. A function can always be used that converts the buffer to a floating point format.
必须手动处理缓冲区,这包括对字节序的更改。始终可以使用将缓冲区转换为浮点格式的函数。
float value = Convert( buffer );
To add, you way of converting the buffer is incorrect:
要添加,您转换缓冲区的方式不正确:
float value = *(float *)buffer;
An array of unsigned chars cannot be simply to a float
type, as it causes undefined behavior. The memory must be copied to an object of type float
:
无符号字符数组不能简单地为float类型,因为它会导致未定义的行为。必须将内存复制到float类型的对象:
float value;
memcpy( &value , buffer , sizeof( value ) ); //assumes endianness has already been handled