1 - 2 of 2 Posts

#### sdt13

·
##### Registered
Joined
·
361 Posts
Discussion Starter · ·
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:
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;
}``````

#### error10

·
##### Premium Member
Joined
·
13,477 Posts
What is this 48, 57, 65, 70, 97, 102 business? You should be checking for the actual characters instead, e.g. '0', '9', 'A', 'F', 'a', 'f'. The reason is your code may run on a system where ASCII is not in use.

I'd probably write something like this:

Code:

Code:
``````long hex_to_dec(char *hex_string)
{
int i;
long result = 0;

for (i = 0; hex_string[i]; ++i) {
result <<= 4;
if (hex_string[i] >= 'a' && hex_string[i] <= 'f') {
result += hex_string[i] - 'a' + 10;    /* a is 10 decimal */
} else if (hex_string[i] >= 'A' && hex_string[i] <= 'F') {
result += hex_string[i] - 'A' + 10;    /* A is 10 decimal */
} else if (hex_string[i] >= '0' && hex_string[i] <= '9') {
result += hex_string[i] - '0';
} else { /* Character isn't 0-9 or A-F or a-f */
return -1;
}
}
return result;
}``````
This lacks range checking (e.g. if the hex value passed is larger than the value a long can store). So watch out for that.

1 - 2 of 2 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.