def _pylong_to_mpz(n, a): """ Set `a` from `n`. :type n: long :type a: mpz_t """ gmp.mpz_set_str(a, hex(n).rstrip('L').encode('UTF-8'), 0)
def _pyint_to_mpz(n, a): """ Set `a` from `n`. :type n: int,long :type a: mpz_t """ if -sys.maxsize - 1 <= n <= sys.maxsize: gmp.mpz_set_si(a, n) elif sys.maxsize < n <= MAX_UI: gmp.mpz_set_ui(a, n) else: gmp.mpz_set_str(a, hex(n).rstrip('L').encode('UTF-8'), 0)
def __init__(self, n=0, base=None): """ mpz() -> mpz(0) If no argument is given, return mpz(0). mpz(n) -> mpz Return an 'mpz' object with a numeric value 'n' (truncating n to its integer part if it's a Fraction, 'mpq', Decimal, float or 'mpfr'). mpz(s[, base=0]): Return an 'mpz' object from a string 's' made of digits in the given base. If base=0, binary, octal, or hex Python strings are recognized by leading 0b, 0o, or 0x characters, otherwise the string is assumed to be decimal. Values for base can range between 2 and 62. """ if isinstance(n, self.__class__): self._mpz = n._mpz return a = self._mpz = ffi.gc(_new_mpz(), _del_mpz) if isinstance(n, str): if base is None: base = 10 if base == 0 or 2 <= base <= 62: if gmp.mpz_set_str(a, n.encode('UTF-8'), base) != 0: raise ValueError("Can't create mpz from %s with base %s" % (n, base)) else: raise ValueError('base must be 0 or 2..62, not %s' % base) elif base is not None: raise ValueError('Base only allowed for str, not for %s.' % type(n)) elif isinstance(n, float): gmp.mpz_set_d(a, n) elif isinstance(n, (int, long)): _pyint_to_mpz(n, a) else: raise TypeError
def __init__(self, n=0, base=None): """ mpz() -> mpz(0) If no argument is given, return mpz(0). mpz(n) -> mpz Return an 'mpz' object with a numeric value 'n' (truncating n to its integer part if it's a Fraction, 'mpq', Decimal, float or 'mpfr'). mpz(s[, base=0]): Return an 'mpz' object from a string 's' made of digits in the given base. If base=0, binary, octal, or hex Python strings are recognized by leading 0b, 0o, or 0x characters, otherwise the string is assumed to be decimal. Values for base can range between 2 and 62. """ if isinstance(n, self.__class__): self._mpz = n._mpz return a = self._mpz = ffi.gc(_new_mpz(), _del_mpz) if isinstance(n, str): if base is None: base = 10 if base == 0 or 2 <= base <= 62: if gmp.mpz_set_str(a, n.encode("UTF-8"), base) != 0: raise ValueError("Can't create mpz from %s with base %s" % (n, base)) else: raise ValueError("base must be 0 or 2..62, not %s" % base) elif base is not None: raise ValueError("Base only allowed for str, not for %s." % type(n)) elif isinstance(n, float): gmp.mpz_set_d(a, n) elif isinstance(n, (int, long)): _pyint_to_mpz(n, a) else: raise TypeError