:
Hi friends,
I need a sample code in C which will convert a Hexadecimal
number into decimal number. I had written a code for that but it was
too long, I need a small code, so request u all to provide me with
small sample code for that.
Your question is very vague and generic, so I'll give you code which is
rather generic.
A number will be represented by a sequence of digits. What's a digit? Is it
a character? Is it a floating-point number? Is it a pointer? I don't know,
so I'll write generic code.
How will we arrange these digits? Well let's decide that we'll have a null-
terminated array which starts with the Most Significant Digit.
In providing a function which converts from one representation to another,
we need also to receive a look-up table to map a digit value to an actual
digit (and vice-versa). This look-up may come in the form of a function, or
of an array. I think a function might be more convenient. Now, we can write
the function as follows:
(Unchecked, may contain a subtle bug or two.)
#include <assert.h>
void ConvertBetweenRadices(DigitType *const p_arr,
unsigned const from_radix,
unsigned (*const pFrom)(DigitType),
unsigned const to_radix,
DigitType (*const pTo)(unsigned))
{
assert(!!p_arr); assert(!!*p_arr); assert(!!from_radix);
assert(!!pFrom); assert(!!to_radix); assert(!!pTo);
{
long unsigned val = 0;
long unsigned multiplier = 1;
DigitType *p = p_arr;
val += pFrom(*p++);
while (*p) val += pFrom(*p++) * (multiplier*=from_radix);
p = p_arr;
do
{
*p++ = pTo(val % to_radix);
val /= to_radix;
} while (val);
*p = 0;
}}
As you can see, the function assumes the precondition that the buffer is
long enough. It may be used something like the following:
(Again, unchecked.)
#include <assert.h>
typedef char DigitType;
#include "cbr.h" /* Code shown above */
unsigned DecToVal(DigitType const x)
{
assert(x>='0' && x<='9');
return x - '0';
}
DigitType ValToHex(unsigned const x)
{
assert(x<=15);
if (x < 10) return '0' + x;
switch(x)
{
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
}
}
#include <stdio.h>
int main(void)
{
char buf[24] = "654323";
ConvertBetweenRadices(buf,10,DecToVal,16,ValToHex);
puts(buf);
return 0;
}
It was only after having written the code that I realised we* write from
left to right putting the Most Significant Digit first, rather than the
Least Significant Digit. Ah well.
*we : except for our Arabic particpants of course!