For a problem at school, I need to convert a ASCII string of character digits to a decimal value. I wrote a function to do this and specified the return type to be an unsigned short as you can see in the code below.
#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;
}
When running this code, the program prints -1 as the final value instead of 65535. It seems it’s displaying the corresponding signed value anyway. Seems like something very simple, but I can’t find an answer. A response would be greatly appreciated.
The problem is that you are taking the
unsigned shortreturn value of the function and storing it in a (signed)shortvariable,input. Since the value is outside the range representable inshort, and sinceshortis signed, this results in either an implementation-defined result or an implementation-defined signal being raised.Change the type of
inputtounsigned shortand everything will be fine.