The program requires an input of an arbitrary large unsigned integer which is expressed as one string in base 10. The outputs is another string that expresses the integer in base 16.
For example, the input is "1234567890987654321234567890987654321234567890987654321", and the output shall be "CE3B5A137DD015278E09864703E4FF9952FF6B62C1CB1"
The faster the algorithm the better.
It will be very easy if the input is limited within 32-bit or 64-bit integer; for example, the following code can do the conversion:
#define MAX_BUFFER 16
char hex[] = "0123456789ABCDEF";
char* dec2hex(unsigned input) {
char buff[MAX_BUFFER];
int i = 0, j = 0;
char* output;
if (input == 0) {
buff[0] = hex[0];
i = 1;
} else {
while (input) {
buff[i++] = hex[input % 16];
input = input / 16;
}
}
output = malloc((i + 1) * sizeof(char));
if (!output)
return NULL;
while (i > 0) {
output[j++] = buff[--i];
}
output[j] = '\0';
return output;
}
The real challenging part is the "arbitrary large" unsigned integer. I have googled but most of them are talking about the conversion within 32-bit or 64-bit. No luck is found.
Can anyone give any hit or any link that can be read on?
Thanks in advance.
Edit This is an interview question I encountered recently. Can anyone briefly explain how to solve this problem? I know there is a gmp library and I utilized it before; however as an interview question it requires not using external library.