将浮点类型转换为两个短字节(高字节和低字节)



我通过解码端的串行端口传输数据。我在传输端编码,按照接收端的编码。我必须将数据从浮点类型(4字节)编码为高部分和低部分(短类型),然后传输它们。

我有解码代码。我必须在编码方面做什么。

我尝试从float realSi转换signed int si,但它是错误的。我得到了signed int si的值0。下面是解码代码。

unsigned short siH = msg->getDataWordArray()[1]
unsigned short siL = msg->getDataWordArray()[2]
signed int si = (siH << 16) | (siL & 0x0000ffff)
float realSi = (float)((float)si)*180/1073741824);

实现这一点的一种方法是使用并集,如下面的示例代码所示。请记住,只有当串行连接两侧的计算机使用相同的浮点格式和相同的端序时,这才会起作用。如果没有,您将需要添加额外的翻译逻辑来处理这些差异。

#include <stdio.h>
union Foo
{
unsigned short asShorts[2];
float asFloat;
};
int main(int, char * *)
{
// Convert a float into two shots
Foo foo;
foo.asFloat = 3.14159f;
printf("For float value %f, the shorts are %u and %un", foo.asFloat, foo.asShorts[0], foo.asShorts[1]);
// [... send the two asShorts values across the serial port here...]

// Imagine this is the receiving-side code (after having received the two shorts)
const unsigned short s1 = foo.asShorts[0];
const unsigned short s2 = foo.asShorts[1];
// Convert the two shorts back into a float
Foo bar;
bar.asShorts[0] = s1;
bar.asShorts[1] = s2;
printf("For shorts %u and %u, the float value is %fn", s1, s2, bar.asFloat);

return 0;
}

顺便说一句,如果你更喜欢发送/接收字节而不是短路,你可以把并集改成这样:

union Foo
{
unsigned char asBytes[4];
float asFloat;
};

最新更新