1

I am writing a base64 encoding method to convert big integer to base64. However, when I test my method I find result is strange. While encode_b64(int('908540701891980503')) method gave me ybyPRoQW0X, however I expect the right ybyPRoQWzX.

def encode_b64(n):
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    result = []
    temp = n
    if 0 == temp:
        return '0'
    else:
        while 0 < temp:
            idx = temp % 64
            result.append(table[idx])
            temp /= 64
            temp = int(temp)
    return ''.join([x for x in reversed(result)])

I have checked several time, but I cannot found logical error. What's wrong with my code?

2 Answers 2

2

You should use integer division here, so temp //= 64 instead of temp /= 64.

def encode_b64(n):
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    if not n:
        return 'A'
    result = []
    while n:
        result.append(table[n % 64])
        n //= 64
    return ''.join(reversed(result))

this gives us:

>>> encode_b64(908540701891980503)
'ybyPRoQWzX'

For small numbers, that will not make a difference, but large floating point numbers have rounding errors, and thus using int(..) might give slightly different results.

If you want to optimize the above a but further, you can use bitwise operations, like:

def encode_b64(n):
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    if not n:
        return 'A'
    result = []
    while n:
        result.append(table[n & 0x3f])
        n >>= 6
    return ''.join(reversed(result))
Sign up to request clarification or add additional context in comments.

Comments

2

This is the classic integer division issue

In python2 temp /= 64 would perform integer division and so your code would work fine. But it in python3, this would result in a float.

To fix the issue in python3, change temp /= 64 to temp //= 64 to force integer division and get rid of the temp = int(temp) line

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.