对于学校的一道题,我需要将一个 ASCII 字符串转换为一个十进制值。我编写了一个函数来执行此操作并将返回类型指定为 unsigned short,如下面的代码所示。
#include <stdio.h>
unsigned short str_2_dec(char* input_string, int numel);
int main()
{
short input;
char input_string[6]= "65535";
input = str_2_dec(input_string, 5);
printf("Final Value: %d", input);
return 0;
}
unsigned short str_2_dec(char* input_string, int numel)
{
int factor = 1;
unsigned short value = 0;
int index;
for(index=0; index <(numel-1); index++)
{
factor *= 10;
}
for(index = numel; index > 0; index--)
{
printf("Digit: %d; Factor: %d; ", *(input_string+(numel-index))-48, factor);
value += factor * ((*(input_string+(numel - index))-48));
printf("value: %d\n\n", value);
factor /= 10;
}
return value;
}
运行此代码时,程序打印 -1
作为最终值而不是 65535
。它似乎无论如何都在显示相应的有符号值。看起来很简单,但我找不到答案。将不胜感激。
最佳答案
str_2_dec()
的返回类型是 unsigned short
但您将值存储在(有符号的)short
变量中。您应该将您的变量声明为适当的类型,否则您将遇到您所观察到的问题。
在这种情况下,您将 "65535"
转换为 unsigned short
,其位模式为 FFFF
Hex。该位模式被重新解释为(带符号的)short
,即十进制值 -1
。
你应该把你的 main()
改成这样:
int main()
{
unsigned short input; /* to match the type the function is returning */
char input_string[6]= "65535";
input = str_2_dec(input_string, 5);
printf("Final Value: %hf", input);
return 0;
}
关于c - 我不希望它返回的类型的函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495056/