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
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=='
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With