问题描述
大家好,
我正在尝试将来自嵌入式传感器设备的一些数据解释为C ++程序.该设备使用称为1.15分数格式的数字格式.这意味着它将2个十六进制字节发送到〜1
本文档中对此格式进行了说明( http://phobos.iet.unipi. it/〜pieri/EdT2/2181_Manual/Appendix_C.pdf [ ^ ]).
我可以理解格式的工作原理(例如,负值的第15位为正),但是我正在努力用C ++实现一个转换器,该转换器可以识别传入数据何时为负.
到目前为止,我具有此功能,但是对于负数它会输出不正确的数据
Hi Everyone,
I''m trying to interpret some data from an embedded sensor device into a C++ program. The device uses a numerical format called 1.15 fractional format. This means it transmits 2 hex bytes into a value rangle of ~1 < n < -1.
A description of the format is given in this document (http://phobos.iet.unipi.it/~pieri/EdT2/2181_Manual/Appendix_C.pdf[^]).
I can understand how the format works (for example, negative values have a positive 15th bit) but I''m struggling to implement a convertor in C++ that can identify when the incoming data is negative.
So far I have this function, but it outputs incorrect data for negative numbers
int Convert(BYTE msg0, BYTE msg1, float Target){
// Combine the 2 bytes
unsigned int F = msg0*256 + msg1;
// display the combined hex bytes and the decimal equivilant
// These values are correct
printf("\n\n Combined F = 0x%x \t F = %i",F,F);
double Ff = (double)F/(32767); // ((2^15)-1) = 32767 = 0x7FFF
printf("\n Ff = %f",Ff);
printf("\n Target = %f",Target);
return 0;
}
目标值取自传感器文档.如您所见,我的正输出非常接近(但不完美),但负值却相去甚远.
目标______十六进制_______输出
0.9999 _____ 0x7FFF ____ 1.000000
0.5 _________ 0x4000 ____ 0.500015
-0.5 ________ 0xC000 ____ 1.500046
-1.0 ________ 0x8000 ____ 1.000031
任何建议都可以收到,我在这里有点儿不了解了!
The Target values are taken from the sensor documentation. As you can see my Positive outputs are pretty close (but not perfect) yet the negative values are way off.
Target______Hex_______Output
0.9999_____0x7FFF____1.000000
0.5_________0x4000____0.500015
-0.5________0xC000____1.500046
-1.0________0x8000____1.000031
Any suggestions greatfully recieved, I''m a little out of my depth here!
推荐答案
// Get the absolute number masking out the sign bit
int n = ((msg0 & 0x7F) << 8) + msg1;
// Get negative number:
// Input masked result
// 0x8000 0x0000 -32768
// ...
// 0xFFFF 0x7FFF -1
if (msg0 & 0x80)
n -= 32768; // 0x8000
// Convert to double according to number of fractional bits
double f = (double)n / ((double)(1 << nFrac));
这篇关于在C ++中以1.15小数格式将十六进制转换为dec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!