cbignumbase-conversion

Algorithm for converting an arbitrarily long String representing a decimal number into a String representing a hexadecimal number


I am currently working on a program in C17, which receives a string from the command line, lets call it st_in. I know that st_in will only contain chars in range [0x30, 0x39], thus represent a decimal number of arbitrary size. I want to convert this string into a string st_out which does represent the same value in hexadecimal, eg. f("123") would yield "7B". The caveat comes from the fact that st_in and st_out can be really big. So I need to convert them digitwise. Is there a standard way of doing it?

All my previous attempts at solving the problem lead me to very complex "ripple-back" ideas, which I can barely grasp conceptually, let alone write down in good ol' C. I also don't really know how to allocate the memory correctly (if n = strlen(st_in) I have found that the maximum number of digits would be ceil(n * log_2(10). But then I need to free just "some" of the memory if the string is shorter.


Solution

  • An algorithm is:

    To multiply the output string by ten and add the new input digit: