如何做数学运算用ASCII? [英] How to do math operations in Ascii?
问题描述
我试图解析纬度,从GPS NMEA数据包经度值。我收到的数据包作为一个字符数组。我分析的纬度数组,现在我需要做的就可以了乘法运算。但它是一个字符数组。例如,下面是一个例子数组:
I'm trying to parse the latitude,longitude values from a GPS NMEA Packet. I receive the packet as a char array. I parsed the latitude array and now i need to do a multiplication operation on it. But it is a char array. For example, here is an example array:
char *latitude;
latitude[0] = '4';
latitude[1] = '0';
latitude[2] = '5';
我想通过2.必须分别输出8,0,10乘以这个值。所以我需要得到4,2,6值作为整数。但是,如果我作为整数使用该数组的内容,它自然输出52,48,53。我不想让这相当于这些ascii字符的整数值,我想要得到的实际值,因为我看到的。
I want to multiply this values by 2. It must output 8,0,10 respectively. So i need to get the 4,2,6 values as integer. But if i use this arrays content as integer, it naturally outputs 52,48,53. I dont want to get the integer value which corresponds these ascii characters, i want to get the actual value as i see.
推荐答案
首先,你要保证人数为单数位或已搬运就位。请大家注意,字符
s时,可以作为没有明确的转换整数,由于整型提升。例如,如果
First of all, you have to ensure the numbers are either single digit or you have handling in place. Please do note that char
s can be used as integers without explicit conversion, due to integer promotion. For instance, if
latitude[0] = '1';
latitude[1] = '3';
latitude[2] = '9';
您必须在一起通过这些分开,然后猫。您可以通过减去获得
,因为所有的个位数字符
的 INT
值0
You have to pass these seperately and then cat them together. You can get the int
value of a char
by subtracting '0'
since all single digit int
values in ascii are sequential to each other. For this, write a function like this:
int asciiToInt (char ascii) {
if ( ascii < '0' || ascii > '9' ) {
return -1; //error
}
else
{
return (int)(ascii - '0'); // This works because '0' has the int value 48 in Ascii and '1' 49 and so on.
}
}
然后调用它像这样
Then call it like this
int a = asciiToInt(latitude[0])*2;
或者,如果你想有一个3位数
Or, if you want to have a 3 digit number
int a;
a = asciiToInt(latitude[0]);
a += asciiToInt(latitude[1])*10;
a += asciiToInt(latitude[2])*100;
a = a*2;
这篇关于如何做数学运算用ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!