我通过串行端口传输数据。在解码方面。我在传输端进行编码,遵循接收端的代码。我必须将数据从浮点类型(4个字节)编码为高部分和低部分(短类型),然后进行传输。
我有解码代码。我必须在编码方面做些什么。
我尝试从signed int si
转换float realSi
,但这是错误的。我得到了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);
答案 0 :(得分:0)
执行此操作的一种方法是使用联合,如下面的示例代码所示。请记住,这仅在串行连接两侧的计算机使用相同的浮点格式和相同的字节序的情况下才有效。如果不是,则需要添加其他翻译逻辑来处理这些差异。
#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 %u\n", 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 %f\n", s1, s2, bar.asFloat);
return 0;
}
...顺便说一句,如果您希望发送/接收字节而不是短裤,则可以将并集改为如下所示:
union Foo
{
unsigned char asBytes[4];
float asFloat;
};