chexbase-conversionbase36

Convert Base 16 (Hexadecimal) to Base 36 String in C


In C, what's an efficient way to convert a 64 character hexadecimal number (as a string) into a base 36 string?

I mean, is it as easy as combining a few GLIB2 functions (on Linux), or Standard Library functions? Or, do I have to do it all custom?


Solution

  • This is easy with a library like GMP:

    mpz_t nr;
    mpz_init(nr);
    mpz_set_str(nr, hexstr, 16);
    printf("%s\n", mpz_get_str(NULL, 36, nr));
    

    On debian-based systems you can install the GMP-library with:

    apt-get install libgmp-dev
    

    Full example:

    #include <stdio.h>
    #include <gmp.h>
    
    int main(int argc, char **argv) {   
        mpz_t nr;
        mpz_init(nr);
        mpz_set_str(nr, argv[1], 16);
        printf("%s\n", mpz_get_str(NULL, 36, nr));
    
        return 0;
    }
    

    Compiled with:

    gcc -O2 conv.c -o conv -lgmp
    

    Performs quite well:

    $ time ./conv 2eb1a3e346933962bdfbb7b118404b68b967d44006986d4b1e88ec23e433de12
    15wa17qx942cddy4n5q5px1fw6yi9llw0lzxjg2ahh2q0w9amq
    
    real    0m0.001s
    user    0m0.000s
    sys     0m0.000s