/* Copyright (c) 2009 Ian Piumarta
 * All rights reserved.
 * See the file COPYING for details.
 */

#include "_mpint.h"

char *mp_cvt(mp_t *mp, int base)
{
  mp_t tmp= MP_INITIALISER;
  mp_copy(&tmp, mp);
  static char *buf= 0;
  static int buflen= 0;
  long len= 0;
  do {
    if (len + 1 > buflen) {
      if (!(buflen *= 2)) buflen= 32;
      buf= buf ? realloc(buf, buflen) : malloc(buflen);
    }
    int d= mp_div_d(&tmp, base);
    if (d > 9) d += 'a' - '9' - 1;
    buf[len++]= '0' + d;
  } while (!mp_zerop(&tmp));
  long a= 0, b= len - 1;
  while (a < b) {
    int c= buf[a];
    buf[a++]= buf[b];
    buf[b--]= c;
  }
  buf[len]= 0;
  mp_clear(&tmp);
  return buf;
}

