Encode string representation of integer to base64 in Python 3

fj123x picture fj123x · Sep 4, 2013 · Viewed 29.5k times · Source

I'm trying to encode an int in to base64, i'm doing that:

foo = 1
base64.b64encode(bytes(foo))

expected output: 'MQ=='

given output: b'AA=='

what i'm doing wrong?

Edit: in Python 2.7.2 works correctly

Answer

doep picture doep · Sep 4, 2013

If you initialize bytes(N) with an integer N, it will give you bytes of length N initialized with null bytes:

>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

what you want is the string "1"; so encode it to bytes with:

>>> "1".encode()
b'1'

now, base64 will give you b'MQ==':

>>> import base64
>>> base64.b64encode("1".encode())
b'MQ=='