Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode string representation of integer to base64 in Python 3 [duplicate]

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

like image 450
fj123x Avatar asked Sep 04 '13 14:09

fj123x


2 Answers

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=='
like image 182
doep Avatar answered Oct 28 '22 12:10

doep


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'.

like image 25
Robᵩ Avatar answered Oct 28 '22 12:10

Robᵩ