1. Read strings using a function you write called getStr ().
2. Write a function named hextodecimal () that takes in (only) a string parameter representing a positive hexadecimal number and return its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters.
-note: you may not use any library functions in this function- you must write all code necessary to enact the coversion and return the appropriate result.
-this function must accept both upper and lower case versions of the hex character.
-You may want to write an additional function that vets any string for invalid hex character
Help writing C language to write hexadecimal to decimal?
This should do to get you started. The reading strings is simple.
#include %26lt;unistd.h%26gt;
#include %26lt;stdio.h%26gt;
unsigned int hex2dec( char *s )
{
unsigned int v = 0;
char *p;
for( p = s; *p; p++ )
{
if( isdigit( *p ) )
v = (v * 16) + (*p - '0');
else
{
*p = tolower( *p );
if( *p %26gt;= 'a' %26amp;%26amp; *p %26lt;= 'f' )
v = (v * 16) + 10 + (*p - 'a');
else
return -1; /* assume illegal hex char */
}
}
return v;
}
main( int argc, char **argv )
{
printf( "%s converts to %u\n", argv[1], hex2dec( argv[1] ) );
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment