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.
Here's a BigInt library:
No idea if it works, but it's the first one I found with Google. It appears to have functions to parse and format big integers, so they may support different bases too.
Edit: Ahh, you're using C, my mistake. But you may be able to pick up ideas from the code, or someone using .NET may have the same question, so I'll leave this here.
Have you tried using GNU MP Bignum library?
I have written an article which describes a simple solution in Python which can be used to transfrom a series of numbers from and to arbitrary number bases. I've originally implemented the solution in C, and I didn't want a dependency to an external library. I think you should be able to rewrite the very easy Python code in C or whatever you like.
Here is the Python code:
Unix
dc
is able to do base conversions on arbitrary large integers. Open BSD source code is available here.Allocate an array of integers, number of elements is equal to the length of the input string. Initialize the array to all 0s.
This array of integers will store values in base 16.
Add the decimal digits from the input string to the end of the array. Mulitply existing values by 10 add carryover, store new value in array, new carryover value is newvalue div 16.
print array, start at 0th entry and skip leading 0s.
Here's some code that will work. No doubt there are probably a few optimizations that could be made. But this should suffice as a quick and dirty solution:
Here is the above-mentioned algorithm implemented in javascript: