xref: /netbsd-src/external/lgpl3/gmp/dist/mpz/out_str.c (revision 63aea4bd5b445e491ff0389fe27ec78b3099dba3)
1 /* mpz_out_str(stream, base, integer) -- Output to STREAM the multi prec.
2    integer INTEGER in base BASE.
3 
4 Copyright 1991, 1993, 1994, 1996, 2001, 2005, 2011, 2012 Free Software
5 Foundation, Inc.
6 
7 This file is part of the GNU MP Library.
8 
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
13 
14 The GNU MP Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18 
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
21 
22 #include <stdio.h>
23 #include "gmp.h"
24 #include "gmp-impl.h"
25 #include "longlong.h"
26 
27 size_t
28 mpz_out_str (FILE *stream, int base, mpz_srcptr x)
29 {
30   mp_ptr xp;
31   mp_size_t x_size = SIZ (x);
32   unsigned char *str;
33   size_t str_size;
34   size_t i;
35   size_t written;
36   const char *num_to_text;
37   TMP_DECL;
38 
39   if (stream == 0)
40     stream = stdout;
41 
42   if (base >= 0)
43     {
44       num_to_text = "0123456789abcdefghijklmnopqrstuvwxyz";
45       if (base <= 1)
46 	base = 10;
47       else if (base > 36)
48 	{
49 	  num_to_text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
50 	  if (base > 62)
51 	    return 0;
52 	}
53     }
54   else
55     {
56       base = -base;
57       if (base <= 1)
58 	base = 10;
59       else if (base > 36)
60 	return 0;
61       num_to_text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
62     }
63 
64   written = 0;
65 
66   if (x_size < 0)
67     {
68       fputc ('-', stream);
69       x_size = -x_size;
70       written = 1;
71     }
72 
73   TMP_MARK;
74 
75   DIGITS_IN_BASE_PER_LIMB (str_size, x_size, base);
76   str_size += 3;
77   str = (unsigned char *) TMP_ALLOC (str_size);
78 
79   xp = PTR (x);
80   if (! POW2_P (base))
81     {
82       xp = TMP_ALLOC_LIMBS (x_size | 1);  /* |1 in case x_size==0 */
83       MPN_COPY (xp, PTR (x), x_size);
84     }
85 
86   str_size = mpn_get_str (str, base, xp, x_size);
87 
88   /* Convert result to printable chars.  */
89   for (i = 0; i < str_size; i++)
90     str[i] = num_to_text[str[i]];
91   str[str_size] = 0;
92 
93   {
94     size_t fwret;
95     fwret = fwrite ((char *) str, 1, str_size, stream);
96     written += fwret;
97   }
98 
99   TMP_FREE;
100   return ferror (stream) ? 0 : written;
101 }
102