2

Ì am able to convert any string containing digits and valid characters (for that base) into an integer by specifying:

print ( int("ABCDEFGHIJKLMN", base=27) ) # for n in [0,2..36]

wich outputs 42246088999001073599. int()

I am interested in the generic reverse of that. (up to 36 would be fine - same as int() does)


Specialized solutions available I know of:

bin() # binary string representation - with prefix
oct() # octal  string representation - with prefix
hex() # hexadecimal string representation - with prefix

str(num[, base=10] ) # for 0, 2..36

or you can use the mini format language to get the "pure" number string:

print(f"{32:o}") #  ==> 40 = 4*8+2=32
Type  Meaning
'b'   Binary format. Outputs the number in base 2.
'o'   Octal format. Outputs the number in base 8.
'x'   Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X'   Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.

I do not know of any generalized int to string of base n method.


I made one for base 12 in my answer to a base 12 question:

class Base12Convert:
    d = {hex(te)[2:].upper():te for te in range(0,12)}
    d.update({val:key for key,val in d.items()})
    d["-"] = "-"

# snipp: def text_to_int(text)

@staticmethod
def int_to_text(num):
    """Converts an int into a base-12 string."""

    sign = ""
    if not isinstance(num,int):
        raise ValueError(
            f"Only integer as input allowed: '{num} of type {type(num)}' is invalid")
    if num < 0:
        sign = "-"
        num *= -1

    # get highest possible number
    p = 1
    while p < num:
        p *= 12

    # create string 
    rv = [sign]
    while True:
        p /= 12
        div = num // p
        num -= div*p
        rv.append(Base12Convert.d[div])
        if p == 1:
            break

    return ''.join(rv)

and could generalize that ... but I probably overlook a built in_one?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • No, you should write it yourself or try looking for modules on PyPI. – iBug Dec 14 '18 at 12:10
  • 2
    There's no generic answer, because there's no "universal dictionary", that will translate your integer to a string. Python chose to use 0-9 + a-z (w/o specifying the case) for base 2-36. But that was their decision. You could chose to translate to a different "dictionary" or even decide to make a difference of upper and lower case. – Mike Scotty Dec 14 '18 at 12:14
  • @MikeScotty there is a dictionary - but it is one-way as `int` maps `A..Z` to `10..35` if you give the correct base - I assumed that they also included an reverse but I never stumbled over it - seems there is none. Thanks. – Patrick Artner Dec 14 '18 at 12:38
  • 1
    I though you meant "generic" in a "for any value of ``n``" sense, so ``n`` could be even bigger than 36, which meant that the Python mapping of 0-9 + A-Z would not be enough. But there's indeed no built-in that I know of to reverse the string for base 2-36. Maybe use one of these: https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string – Mike Scotty Dec 14 '18 at 12:48
  • @MikeScotty that did not pop up in my searched -thx. Closed as dupe. – Patrick Artner Dec 14 '18 at 12:57

0 Answers0