我有一个程序需要占用4个字节并将它们转换为IEEE-754浮点数.字节不按顺序传输,但我可以把它们按顺序放回去.我的问题是把它们扔到浮子上.代码的相关部分:
//Union to store bytes and float on top of each other
typedef union {
unsigned char b[4];
float f;
} bfloat;
//Create instance of the union
bfloat Temperature;
//Add float data using transmitted bytes
MMI.Temperature.b[2] = 0xD1;//MMIResponseMsg[7];
MMI.Temperature.b[3] = 0xE1;//MMIResponseMsg[8];
MMI.Temperature.b[0] = 0x41;//MMIResponseMsg[9];
MMI.Temperature.b[1] = 0xD7;//MMIResponseMsg[10];
//Attempting to read the float value
lWhole=(long) ((float)MMI.Temperature.f);
//DEBUGGING
stevenFloat = (float)MMI.Temperature.f;
Run Code Online (Sandbox Code Playgroud)
lWhole很长,stevenFloat是一个漂浮.当调试我可以看到,我分配给字节数组中的值被正确地存储,然而的值stevenFloat和lWhole不正确.它们似乎悬停在接近0或接近最大浮点数/长值的位置.使用我的编译器,long和float都是32位.
有谁知道为什么这不起作用?当我收到要处理的代码时看起来对我来说是正确的,它似乎是一个在线的常见解决方案,我只是难倒.
我正在尝试从字符串读取gps读取到我的Arduino上的浮点数.字符串全部处理所有数字就好了,但是当我将它除去得到一个浮点数时,我失去了4个数字.这是我的代码:
gpsStrings[0].replace(".", "");
lat = gpsRawData[0].toFloat();
lat = lat / 1000000.0;
Run Code Online (Sandbox Code Playgroud)
在仍然包含小数点的字符串上使用.toFloat会产生相同的结果,小数点后只有两个数字.
示例数字:
42427898 :: 42.43 - what happens
42427898 :: 42.427898 - what I want to happen
Run Code Online (Sandbox Code Playgroud) 我在程序中使用clock_gettime.我试过包括但是没有效果.我还为我的编译器参数添加了-lrt但仍然得到相同的错误.
这是开启
CentOS Linux release 7.2.1511 (Core)
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
GNU ld version 2.23.52.0.1-55.el7 20130226
ldd (GNU libc) 2.17
Run Code Online (Sandbox Code Playgroud)
编译器输出:
gcc -o main packet.c connect.c transport.c accept.c main.c close.c util.c receive.c send.c congestion.c -Wall -g -std=c99 -lrt
util.c: In function ‘millis’:
util.c:42:21: error: storage size of ‘t’ isn’t known
struct timespec t;
^
util.c:43:5: warning: implicit declaration of function ‘clock_gettime’ [-Wimplicit-function-declaration]
clock_gettime(CLOCK_MONOTONIC_RAW, &t);
^
util.c:43:19: error: ‘CLOCK_MONOTONIC_RAW’ undeclared (first use in this function)
clock_gettime(CLOCK_MONOTONIC_RAW, &t);
^ …Run Code Online (Sandbox Code Playgroud)