Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert int to other bases
#4
This one creates strings suitable for putting back into int(x, base=36). Not as useful for arbitrarily large bases.

import string
import random

base = 36
mapping = string.digits + string.ascii_uppercase

def int_to_other_base(num, base):
    ans = ""
    while num > 0:
        num, remainder = divmod(num, base)
        ans = mapping[remainder] + ans
    return ans

num = random.randint(0,1000000000000000)

print(f"For integer {num}")
rebased = int_to_other_base(num,base)
print(f"In base {base}: {rebased}")
print(f"and converted back to an int: {int(rebased,base)}")
Output:
For integer 19520920808903 In base 36: 6X3SC8FRB and converted back to an int: 19520920808903
Reply


Messages In This Thread
convert int to other bases - by Skaperen - Sep-29-2020, 06:11 PM
RE: convert int to other bases - by bowlofred - Sep-29-2020, 06:22 PM
RE: convert int to other bases - by buran - Sep-29-2020, 06:30 PM
RE: convert int to other bases - by bowlofred - Sep-29-2020, 06:46 PM
RE: convert int to other bases - by buran - Sep-29-2020, 07:00 PM
RE: convert int to other bases - by Skaperen - Sep-30-2020, 04:08 AM
RE: convert int to other bases - by bowlofred - Sep-30-2020, 04:56 AM
RE: convert int to other bases - by Skaperen - Sep-30-2020, 10:03 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020