3

I am attempting to convert base 16 to base 36. I'm taking md5 hashes and making them have all 0-9a-z.

I searched around and didn't find anything good. Any suggestions for converting hexadecimal to hexatridecimal in c++? Do you guys know any good libraries for doing it?

Jörgen Sigvardsson
  • 4,839
  • 3
  • 28
  • 51
Tech163
  • 4,176
  • 8
  • 33
  • 36
  • i don't understand the question :$ – ykatchou Dec 29 '10 at 14:03
  • How do I convert convert 098f6bcd4621d373cade4e832627b4f6 from base 16 to base 36 in C++? – Tech163 Dec 29 '10 at 14:04
  • I will post C++ code later which does what you want, but in the meantime, this post is related: http://stackoverflow.com/questions/3419606/compress-21-alphanumeric-characters-in-to-16-bytes – John Dibling Dec 29 '10 at 14:14
  • The Any Base Calculator (http://play.google.com/store/apps/details?id=com.ewe.radixcalculator) in the Android Play Market can do that. It can be used to convert between base 16 and base 36. It is free. – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz Apr 01 '12 at 19:21

2 Answers2

3

The basic solution is to convert your 128-bit number to a (large) integer, then subsequently perform modulus and divide operations by 36.

However, if you're OK with wasting a couple of bits, why not convert to base 32 to make things easier? Then you can do everything with shifting and masking.

Frederik Slijkerman
  • 6,471
  • 28
  • 39
  • 3
    Another simple idea would be to use base64; it has several advantages: it's widespread (lots of tools to convert from/to it), is easily recognizable, and you can perform the conversion easily. – Matteo Italia Dec 29 '10 at 14:14
  • 1
    Base-64 is also very popular (uses digits, upper and lower-case letters, and a few punctuation like underscore and hyphen), and there are plenty of functions around to do that conversion. – Ben Voigt Dec 29 '10 at 14:19
  • @John Could you explain? I was under the impression that one of the major strengths of Base64 is that it can in fact represent binary data in printable ASCII form. – Abe Voelker Dec 29 '10 at 16:12
  • @Abe: You are correct, bas64 *does* use only low-ascii printable characters. I'll delete my previous comment. – John Dibling Dec 29 '10 at 16:17
3

I assume the tricky part you're struggling with is the conversion to Rad36, not getting a integral value from a hex number represented as a string. So, here is a function which takes an unsigned __int64, converts it to Radix 36, and returns a string with the converted value.

string rad36(unsigned __int64 v)
{
    string retval;
    while( v > 0 )
    {
        unsigned m = v%36;
        if( m <= 9 )
            retval.insert(0,1,'0'+m);
        else
            retval.insert(0,1,'A'+m-10);
        v /= 36;
    }
    return retval;
}
John Dibling
  • 99,718
  • 31
  • 186
  • 324