1 /* mpz_get_str (string, base, mp_src) -- Convert the multiple precision
2 number MP_SRC to a string STRING of base BASE. If STRING is NULL
3 allocate space for the result. In any case, return a pointer to the
4 result. If STRING is not NULL, the caller must ensure enough space is
5 available to store the result.
7 Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2002, 2005 Free Software
10 This file is part of the GNU MP Library.
12 The GNU MP Library is free software; you can redistribute it and/or modify
13 it under the terms of the GNU Lesser General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or (at your
15 option) any later version.
17 The GNU MP Library is distributed in the hope that it will be useful, but
18 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
20 License for more details.
22 You should have received a copy of the GNU Lesser General Public License
23 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
25 #include <string.h> /* for strlen */
31 mpz_get_str (char *res_str, int base, mpz_srcptr x)
34 mp_size_t x_size = x->_mp_size;
38 size_t alloc_size = 0;
45 num_to_text = "0123456789abcdefghijklmnopqrstuvwxyz";
50 num_to_text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
58 num_to_text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
61 /* allocate string for the user if necessary */
64 /* digits, null terminator, possible minus sign */
65 MPN_SIZEINBASE (alloc_size, PTR(x), ABS(x_size), base);
66 alloc_size += 1 + (x_size<0);
67 res_str = (char *) (*__gmp_allocate_func) (alloc_size);
77 /* mpn_get_str clobbers its input on non power-of-2 bases */
82 xp = TMP_ALLOC_LIMBS (x_size + 1); /* +1 in case x_size==0 */
83 MPN_COPY (xp, x->_mp_d, x_size);
86 str_size = mpn_get_str ((unsigned char *) res_str, base, xp, x_size);
87 ASSERT (alloc_size == 0 || str_size <= alloc_size - (SIZ(x) < 0));
89 /* might have a leading zero, skip it */
91 if (*res_str == 0 && str_size != 1)
95 ASSERT (*str != 0); /* at most one leading zero */
98 /* Convert result to printable chars, and move down if there was a leading
100 for (i = 0; i < str_size; i++)
101 res_str[i] = num_to_text[(int) str[i]];
102 res_str[str_size] = 0;
106 /* if allocated then resize down to the actual space required */
109 size_t actual_size = str_size + 1 + (res_str - return_str);
110 ASSERT (actual_size == strlen (return_str) + 1);
111 __GMP_REALLOCATE_FUNC_MAYBE_TYPE (return_str, alloc_size, actual_size,