I'm learning C and one of the questions I've been asked is converting a string to an integer. The code I've written supports converting from a string in any base up to 16/hex to an integer. There is no over/underflow checking and it does not support lowercase hex.
int ASCIIToInteger(char *x, int base)
{
//Each element is the ASCII for it's index.
int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; _Bool negative = 0;
int count = 0, output = 0;
if (x[0] == '-')
{
negative = 1;
count = 1;
}
else if (x[0] == '+')
{
count = 1;
}
do
{
for (int i = 0; i < base; i++)
{
if (ASCIICodes[i] == (int)x[count])
{
output = output * base + i;
break;
}
}
count++;
} while (x[count] != 0);
if (negative == 1)
{
return ~output + 1;
}
return output;
}
Can I please get some advice regarding any possible issues or "rookie mistakes" I may have made?
strtol
(2) function? \$\endgroup\$