H
Herrcho
Hi~ i've studied C for a few months myself,
and i'd appreciate it if anyone could improve my coding or correct it.
the following is my solution to the K&R exercise 2-3
"Write the function htoi(s), which converts a string of hexademical digits
(including an optional 0x or 0X) into its equivalent integer value.
The allowable digits are 0 through 9, a through f, and A throught F."
//**************************************************************************
#include <stdio.h>
int isxdigit2(int c)
{
if ( (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9') )
return 1;
else
return 0;
}
int tolower2(int c)
{
if (c >= 'A' && c <= 'Z')
return c+32;
else
return c;
}
int power2(int base, int num)
{
int sum;
for (sum = 1; num >0 ; num --)
sum *= base;
return sum;
}
int char_to_num(int c)
{
if (c >= '0' && c <= '9')
{
return c - 48;
}
else
{
return 10 + (tolower2(c) - 'a');
}
}
int htoi(char *c)
{
int i, k, prefix = 0;
size_t sum = 0;
if (c[0] == '0' && tolower2(c[1]) == 'x')
prefix = 1;
for (i = (prefix == 1)? 2:0 ; c ;i++ )
{
if (!isxdigit2(c) )
{
printf("Wrong hexa number\n");
return 0;
}
c = char_to_num(c);
}
for (k = (prefix == 1)? 2 : 0 ; k <= i-1 ; ++k )
{
sum += c[k] * power2(16, i-1-k);
}
return sum;
}
int main()
{
char c[] = "0xAB";
printf("%u", htoi(c));
return 0;
}
//******************************************************************
when i change char c[] to char *c in main(),
it shows error, why ??
Thanks..
and i'd appreciate it if anyone could improve my coding or correct it.
the following is my solution to the K&R exercise 2-3
"Write the function htoi(s), which converts a string of hexademical digits
(including an optional 0x or 0X) into its equivalent integer value.
The allowable digits are 0 through 9, a through f, and A throught F."
//**************************************************************************
#include <stdio.h>
int isxdigit2(int c)
{
if ( (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9') )
return 1;
else
return 0;
}
int tolower2(int c)
{
if (c >= 'A' && c <= 'Z')
return c+32;
else
return c;
}
int power2(int base, int num)
{
int sum;
for (sum = 1; num >0 ; num --)
sum *= base;
return sum;
}
int char_to_num(int c)
{
if (c >= '0' && c <= '9')
{
return c - 48;
}
else
{
return 10 + (tolower2(c) - 'a');
}
}
int htoi(char *c)
{
int i, k, prefix = 0;
size_t sum = 0;
if (c[0] == '0' && tolower2(c[1]) == 'x')
prefix = 1;
for (i = (prefix == 1)? 2:0 ; c ;i++ )
{
if (!isxdigit2(c) )
{
printf("Wrong hexa number\n");
return 0;
}
c = char_to_num(c);
}
for (k = (prefix == 1)? 2 : 0 ; k <= i-1 ; ++k )
{
sum += c[k] * power2(16, i-1-k);
}
return sum;
}
int main()
{
char c[] = "0xAB";
printf("%u", htoi(c));
return 0;
}
//******************************************************************
when i change char c[] to char *c in main(),
it shows error, why ??
Thanks..