Itoa for Base-10 to base-36

Oct 5, 2014 at 1:48am
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?
Oct 5, 2014 at 2:24am
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 Oct 5, 2014 at 4:07am
Oct 5, 2014 at 3:01am
closed account (48T7M4Gy)
http://en.wikipedia.org/wiki/Base_36
Oct 5, 2014 at 3:28am
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.
Oct 5, 2014 at 4:10am
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?
Oct 5, 2014 at 7:39am
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.