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'.
AQ== instead of MQ==MQ==.struct module to do b64encode(pack('<Q', foo).rstrip('\x00') or '\x00').rstrip('=') which will give you a much shorter encoded string for big integers.base64.b64encode(i.to_bytes(ceil(i.bit_length()/8),'big')) Question should NOT be closed.base64.b64encode(i.to_bytes((i.bit_length()+8)//8,'big',signed=True)) to get signed converted correctly. and int.from_bytes(base64.b64decode(z),'big',signed=True) to decode signed ( i switched to using +8 ... //8 instead of ceil... one less library, and it gives you the extra bit you need for the sign)
b'AA=='. The problem is notb64encode, it isbytes(). In Python3,bytes(1)returnsb'00'.