How to do math operations in Ascii?

泪湿孤枕 提交于 2020-01-07 03:07:33

问题


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';

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.


回答1:


First of all, you have to ensure the numbers are either single digit or you have handling in place. Please do note that chars can be used as integers without explicit conversion, due to integer promotion. For instance, if

latitude[0] = '1';
latitude[1] = '3';
latitude[2] = '9';

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;

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;



回答2:


Try to convert char to int via subtracting '0' from it. Example:

int doubledLatitude[3];
for (size_t i = 0; i < 3; ++i)
    doubledLatitude[i] = (latitude[i] - '0') * 2;



回答3:


First, you should specify exactly the input perhaps using EBNF notation and decide what the program should do on errors. A single example is never enough! See this

To convert the single character '4' to the integer 4, you could use ('4' - '0') (since the difference of chars is promoted to int), so I guess you want something like (latitude[0] - '0')*2 which you might print with printf("%d",(latitude[0] - '0')*2)

BTW, if your strings of digits contain one or several digits, you could use strtol to convert them to some long (e.g. "123 " converted to 123L) , and get the ending character (hence being able to detect and handle errors).

And you could also use sscanf; notice that it returns the number of scanned items (which you should always test) and what %d, %1d and %n means in the format string.



来源:https://stackoverflow.com/questions/34716842/how-to-do-math-operations-in-ascii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!