如何在 Ascii 中进行数学运算?

How to do math operations in Ascii?

我正在尝试解析来自 GPS NMEA 数据包的纬度、经度值。我收到的数据包是一个字符数组。我解析了纬度数组,现在我需要对其进行乘法运算。但它是一个字符数组。例如,这是一个示例数组:

char *latitude;

latitude[0] = '4';
latitude[1] = '0';
latitude[2] = '5';

我想把这个值乘以2。它必须分别输出8,0,10。所以我需要将 4、2、6 值作为整数获取。但是,如果我将此数组内容用作整数,它自然会输出 52、48、53。我不想得到对应这些 ascii 字符的整数值,我想得到我看到的实际值。

首先,您应该准确指定输入,也许使用EBNF notation and decide what the program should do on errors. A single example is never enough! See this

要将单个字符 '4' 转换为整数 4,您可以使用 ('4' - '0')(因为 chars 的差异被提升为 int),因此我猜你想要像 (latitude[0] - '0')*2 这样的东西,你可以用 printf("%d",(latitude[0] - '0')*2)

打印

顺便说一句,如果您的数字串包含一个或多个数字,您可以使用 strtol 将它们转换为一些 long(例如 "123 " 转换为 123L ) ,并获取结束字符(因此能够检测和处理错误)。

你也可以使用 sscanf;请注意它 returns 扫描项目的数量(您应该始终测试)以及 %d%1d%n 在格式字符串中的含义。

尝试通过从中减去 '0' 将 char 转换为 int。 示例:

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

首先,您必须确保这些数字是个位数或者您已经进行了适当的处理。请注意,由于整数提升,chars 可以用作整数而无需显式转换。例如,如果

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

你必须单独传递这些,然后将它们放在一起。您可以通过减去 '0' 来获得 charint 值,因为 ascii 中的所有单个数字 int 值都是彼此连续的。为此,编写如下函数:

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.
}
}

然后这样称呼它

int a = asciiToInt(latitude[0])*2;

或者,如果您想要一个 3 位数的号码

int a;
a = asciiToInt(latitude[0]);
a += asciiToInt(latitude[1])*10;
a += asciiToInt(latitude[2])*100;
a = a*2;