【发布时间】:2019-06-22 05:29:31
【问题描述】:
编写一个 C 函数,它接受一个以 null 结尾的字符串,包含一个十六进制字符串,并返回整数值。您不能调用任何 C 库函数,除了 strlen() 对函数进行编码。十进制字符串将仅包含从“0”到“9”和“A”到“F”的 0-4 个 ASCII 字符。不需要错误处理。如果字符串为空,则返回值 0。
我一直在尝试修复我的错误,但是一旦我修复了它们,就会弹出新的错误,导致我感到困惑。
#include <stdlib.h> /*used for EXIT_SUCCESS */
#include <stdio.h> /*used for printf */
#include <string.h> /* used for strlen */
#include <stdbool.h> /* used for bool */
#include <math.h>
unsigned int hexStringTouint(const char str[], int length, int n[])
{
int i, j;
int intvalue = 0;
int digit;
for(i = (length-1), j = 0; i --, j++)
{
if(n[i]>='0' && n[i] <='9')
{
digit = n[i] - 0x30;
}
else if(n[i]>= 'A' && n[i] <= 'F')
{
switch(n[i])
{
case 'A': digit = 10; break;
case 'B': digit = 11; break;
case 'C': digit = 12; break;
case 'D': digit = 13; break;
case 'E': digit = 14; break;
case 'F': digit = 15; break;
}
}
intvalue += digit*pow(16,j);
}
printf("int value is %d\n", intvalue);
return 0;
}
int main(void)
{
int i, length, intvalue;
unsigned char n[] = "";
printf("Enter your hexadecimal string: ");
scanf("%c\n", n);
intvalue = 0;
length = strlen(n);
return EXIT_SUCCESS;
}
我收到错误消息说
expected ';' in 'for' statement specifier
以及 const char* 如何在指针和整数之间进行转换。
【问题讨论】:
-
需要 3 个语句。你错过了打破循环的条件。在你的情况下应该是
for(i = (length-1), j = 0; i >= 0; i --, j++)。 -
不要使用
pow(16,j)。请改用1 << j*4 -
提示:如果
char c是当前十六进制字符的变量:数字'0'到'9'的值是c - '0'。类似地,数字'A'到'F'的值是c - 'A' + 0xa。通常,接受大写字母和小写字母。在这种情况下,toupper(c)不会受到伤害。 (它不会改变任何非字母字符。)总而言之:if (isxdigit(c)) digit = isdigit(c) ? c - '0' : toupper(c) - 'A' + 0xa;- 一个衬里...... ;-)
标签: c