Itoa for Base-10 to base-36

I am using itoa to convert base-10 to base-36 but it seems to be only be able to produce base-36 string of up to 6 characters. For my project I need at least 12. Is there any other version of this algorithm or another algorithm entirely that anyone knows about that could accomplish this?
You'd have to do it yourself, alas. (itoa() doesn't have the range.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
template <typename T>
char* itoa2( T value, char* str, T base )
{
  if (!value)
  {
    str[0] = '0';
    str[1] = '\0';
    return str;
  }

  bool negative = value < 0;
  if (negative) value = -value;

  // generate the string
  char* p = str;
  while (value)
  {
    T digit = value % base;
    *p++ = (digit < 10) ? ('0' + digit) : ('A' + digit - 10);
    value /= base;
  }
  if (negative) *p++ = '-';
  *p-- = '\0';

  // reverse the string
  char* q = str;
  while (p > q)
  {
    char c = *p;
    *p-- = *q;
    *q++ = c;
  }

  return str;
}

Untested!

Hope this helps.

[edit] Fixed stupid bug.
Last edited on
closed account (48T7M4Gy)
http://en.wikipedia.org/wiki/Base_36
Thanks for your reply! I will take your advice and try to do this myself. The code you posted didn't work(same problem with range and isn't accurate). If you find the solution please let me know otherwise I will post the code when I figure it out.
Sorry, I made a stupid mistake when reversing the final string. I fixed it, now the function will work.

There is no reason you should be having range issues. How are you calling the function?
http://www.strudel.org.uk/itoa/
You might need to expand string literal to support base36 for some examples.
Topic archived. No new replies allowed.