1 /* mpz_set_str(mp_dest, string, base) -- Convert the \0-terminated
2 string STRING in base BASE to multiple precision integer in
3 MP_DEST. Allow white space in the string. If BASE == 0 determine
4 the base in the C standard way, i.e. 0xhh...h means base 16,
5 0oo...o means base 8, otherwise assume base 10.
7 Copyright 1991, 1993, 1994, 1996, 1997, 1998, 2000, 2001, 2002, 2003, 2005
8 Free Software Foundation, Inc.
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/. */
30 extern const unsigned char __gmp_digit_value_tab
[];
31 #define digit_value_tab __gmp_digit_value_tab
34 mpz_set_str (mpz_ptr x
, const char *str
, int base
)
42 const unsigned char *digit_value
;
45 digit_value
= digit_value_tab
;
48 /* For bases > 36, use the collating sequence
49 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. */
52 return -1; /* too large base */
55 /* Skip whitespace. */
57 c
= (unsigned char) *str
++;
64 c
= (unsigned char) *str
++;
67 if (digit_value
[c
] >= (base
== 0 ? 10 : base
))
68 return -1; /* error if no valid digits */
70 /* If BASE is 0, try to find out the base by looking at the initial
78 c
= (unsigned char) *str
++;
79 if (c
== 'x' || c
== 'X')
82 c
= (unsigned char) *str
++;
84 else if (c
== 'b' || c
== 'B')
87 c
= (unsigned char) *str
++;
92 /* Skip leading zeros and white space. */
93 while (c
== '0' || isspace (c
))
94 c
= (unsigned char) *str
++;
95 /* Make sure the string does not become empty, mpn_set_str would fail. */
103 str_size
= strlen (str
- 1);
104 s
= begs
= (char *) TMP_ALLOC (str_size
+ 1);
106 /* Remove spaces from the string and convert the result from ASCII to a
108 for (i
= 0; i
< str_size
; i
++)
112 int dig
= digit_value
[c
];
120 c
= (unsigned char) *str
++;
125 xsize
= 2 + (mp_size_t
)
126 (str_size
/ (GMP_NUMB_BITS
* mp_bases
[base
].chars_per_bit_exactly
));
127 MPZ_REALLOC (x
, xsize
);
129 /* Convert the byte array in base BASE to our bignum format. */
130 xsize
= mpn_set_str (x
->_mp_d
, (unsigned char *) begs
, str_size
, base
);
131 x
->_mp_size
= negative
? -xsize
: xsize
;