Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert base 10 integers to base 80 in Python without encountering IndexError?

I’m working on a Python script where I need to convert base 10 integers to base 80 using a specific set of characters. I’ve implemented a function for this purpose, but I keep encountering an IndexError due to the index going out of range. Here’s the function I’m using:

def base10_to_base80(n):
    base_80 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~!$&\'()*+,:;=/'  # Corrected string
    if n == 0:
        return base_80[0]
    digits = []
    while n:
        digits.append(base_80[n % 80])
        n //= 80
    return ''.join(digits[::-1])

# Example usage:
decimal_number = 79
base_80_number = base10_to_base80(decimal_number)
print(base_80_number)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are getting this error because

base_80 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~!$&\'()*+,:;=/

len(base_80) is 79

you need one more character in base_80 to make it work properly.



Your current code will work for base 79 you can just modify:

digits.append(base_80[n % 79])
        n //= 79

your code will work good.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading