Search code examples
pythongmpy

gmpy2 mpz type in a different base


I am trying to use MPZ to change the base of a number, but when I try mpz(16[, base=16]) I get an invalid syntax error.

If I use mpz(0x16), it returns a base 10 number (22). Is it possible to store an MPZ type in a different base?


Solution

  • The mpz type always stores the value internally as binary. The optional base keyword is used for string conversion. Some examples:

    >>> mpz("10", base=16)
    mpz(16)
    >>> mpz("10", base=32)
    mpz(32)
    

    To convert an mpz to a string in an arbitrary base, uses the digits() method.

    >>> mpz("10", base=32).digits(16)
    '20'
    >>> mpz("10", base=32).digits(32)
    '10'
    >>> mpz("10", base=32).digits(2)
    '100000'
    

    Regarding the syntax error, the square brackets in the help text [, base=0] indicated that the keyword base is optional and the default value is 0. The square brackets should not be entered.