I have an assignment that i could use some help on.
Write a function named hexToDecimal() that takes in (only) a string parameter representing a hexadecimal number and returns its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters. Cannot use any library functions. Must be case insensitive (i.e A, a are same). So far i have the beginning in which it checks if it is a 0-9. a-f, or A-F.
I am thinking storing each ASCII value in temp, changing it to its hex digit, then converting it to decimal and adding it to sum
P.S. there is a check for null (\\ 0) in the for loop it wont show in the forum.
Code:
Write a function named hexToDecimal() that takes in (only) a string parameter representing a hexadecimal number and returns its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters. Cannot use any library functions. Must be case insensitive (i.e A, a are same). So far i have the beginning in which it checks if it is a 0-9. a-f, or A-F.
I am thinking storing each ASCII value in temp, changing it to its hex digit, then converting it to decimal and adding it to sum
P.S. there is a check for null (\\ 0) in the for loop it wont show in the forum.
Code:
Code:
{
int i, count = 0, temp, sum = 0, j = -2;
for(i = 0; str[i] != '\0'; i++)
{
if( ( (int) str[i] < 48 || (int) str[i] > 57) && ( (int) str[i] < 65 || (int) str[i] > 70) && ( (int) str[i] < 97 || (int) str[i] > 102 ))
return -1;
count++;
}
count--;
for(count; count >= 0; count--)
{
if( str[count] >= '0' && str[count] <= '9')
temp = str[count] - 48;
else if ( str[count] >= 'A' && str[count] <= 'F')
temp = str[count] - 55;
else
temp = str[count] - 87;
for(i = 0; i < count; i++)
temp = temp * 16 << (j + 2);
}
printf("%in", temp);
return temp;
}