Encode string representation of integer to base64 in Python 3
Try this:
foo = 1
base64.b64encode(bytes([foo]))
or
foo = 1
base64.b64encode(bytes(str(foo), 'ascii'))
# Or, roughly equivalently:
base64.b64encode(str(foo).encode('ascii'))
The first example encodes the 1-byte integer 1
. The 2nd example encodes the 1-byte character string '1'
.
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=='