我有一个将记录的信息存储为.pcap文件的传感器。我设法将文件加载到一个未签名的char数组中。传感器以唯一的格式存储信息。例如,代表290.16的角度,它将信息存储为二进制等效值0x58 0x71。
为了获得正确的角度,我要做的是将0x71和0x58连接起来,然后将所得的十六进制值转换为十进制除以100的十进制值,然后将其存储以进行进一步分析。
我当前的方法是这样的:
//all header files are included
main
{
unsigned char data[50]; //I actually have the data loaded in this from a file
data[40] = 0x58;
data[41] = 0x71;
// The above maybe incorrect. What i am trying to imply is that if i use the statement
// printf("%.2x %.2x", data[40],data[41]);
// the resultant output you see on screen is
// 58 71
//I get the decimal value i wanted using the below statement
float gar = hex2Dec(dec2Hex(data[41])+dec2Hex(data[40]))/100.0;
}
hex2Dec和dec2Hex是我自己的函数。
unsigned int hex2Dec (const string Hex)
{
unsigned int DecimalValue = 0;
for (unsigned int i = 0; i < Hex.size(); ++i)
{
DecimalValue = DecimalValue * 16 + hexChar2Decimal (Hex[i]);
}
return DecimalValue;
}
string dec2Hex (unsigned int Decimal)
{
string Hex = "";
while (Decimal != 0)
{
int HexValue = Decimal % 16;
// convert deimal value to a Hex digit
char HexChar = (HexValue <= 9 && HexValue >= 0 ) ?
static_cast<char>(HexValue + '0' ) : static_cast<char> (HexValue - 10 + 'A');
Hex = HexChar + Hex;
Decimal = Decimal /16;
}
return Hex;
}
int hexChar2Decimal (char Ch)
{
Ch= toupper(Ch); //Change the chara to upper case
if (Ch>= 'A' && Ch<= 'F')
{
return 10 + Ch- 'A';
}
else
return Ch- '0';
}
痛苦的是,我必须进行数十亿次转换,这确实减慢了该过程。还有其他有效的方法来处理这种情况吗?
我的朋友为类似的传感器开发的matlab代码花了他3个小时来提取仅价值1分钟实时的数据。我真的需要尽快。
据我所知,这与
float gar = ((data[45]<<8)+data[44])/100.0;
对于:
unsigned char data[50];
data[44] = 0x58;
data[45] = 0x71;
值gar
会290.16
。
说明:
不必将整数的值转换为字符串以获取十六进制值,因为十进制,十六进制,二进制等仅是同一值的不同表示形式。data[45]<<8
将data[45]
八位的值向左移动。在执行操作之前,将操作数的类型提升为int
(可能是某些异常的实现除外unsigned int
),因此新数据类型应足够大而不会溢出。向左移动八位等效于十六进制表示形式向左移动两位数。结果是0x7100
。然后将的值data[44]
添加到该值,您将得到0x7158
。int
然后将type的结果强制转换为float
并除以100.0
。
通常,int
如果它只有16位长,可能太小而无法应用移位操作而不移位符号。如果要解决这种情况,请显式转换为unsigned int
:
float gar = (((unsigned int)data[45]<<8)+data[44])/100.0;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句