If you want to convert a hex string to decimal, you
need to do two operations:
- convert the hex string to a number
- generate a decimal string from that number
If your system supported a full C implementation,
it would be as simple as using scanf()/printf().
I presume you're being asked to implement the
primitives yourself :-)
To convert a hex string to a number, you might
implement something like:
int number = 0;
while ((c = getchar()) != '\n') {
if (c >= '0' && c <= '9')
number = (number<<4) + (c-'0')
else if (c>='a' && c<='f')
number = (number<<4) + (c-'a')
else if (c>='A' && c<='F')
number = (number<<4) + (c-'A')
}
This could be cleaned up if you have access to the
macros [ie. isdigit() and tolower()].
To convert the number to a decimal string, you need
to perform successive divisions by 10. An 8051
doesn't have a hardware divide, but that's OK
because you should have a software divide/remainder
subroutine.
There are two tricks to keep in mind. First to
generate the appropriate character for each digit,
you can treat a literal character string as an
array. For example:
char c = "0123456789ABCDEF"[i];
will assign the correct character to variable "c"
based on the value of "i" (if it is between 0 and
15).
The other detail is that as you call the divide/
remainder subroutine, you will generate the digits
working from least significant to most significant.
Therefore, you'll want to fill an array from right
to left. Assuming you have a divide routine with
the prototype:
int
divide(int dividend, int divisor, int *remainder)
and you can use the "puts()" function to display the
generated string, you might use something like:
void
todecimal(int value)
{
char buffer[20];
char*p = &buffer[sizeof(buffer)-1];
int remainder;
while (value != 0) {
value = divide(value, 10, &remainder);
*p-- = "0123456789ABCDEF"[remainder];
}
puts(p+1);
}