20

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

9
  • 1
    Hmm... what version of Python are you using? When I do base64.b64encode(bytes(1)) or foo=1;base64.b64encode(bytes(foo)) I'm getting 'MQ=='. Also, where are you running this on? Commented Sep 4, 2013 at 14:36
  • 1
    When I run your code, I have the expected output. Did you redefine foo somewhere else? try base64.b64encode(b'1') Commented Sep 4, 2013 at 14:38
  • i'm using Python 3.3.2 Commented Sep 4, 2013 at 14:38
  • 1
    Confirmed: in Python 3.1.2 it prints b'AA=='. The problem is not b64encode, it is bytes(). In Python3, bytes(1) returns b'00'. Commented Sep 4, 2013 at 14:40
  • 2
    NOTE: This is definitely not a duplicate. And none of the answers below are correct. See comments. Commented Aug 1, 2018 at 18:54

2 Answers 2

16

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=='
Sign up to request clarification or add additional context in comments.

1 Comment

base64.b64encode(i.to_bytes(ceil(i.bit_length()/8),'big'))
5

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

9 Comments

this is returning AQ== instead of MQ==
The 2nd example returns MQ==.
For others who want to encode integers but don't have expected output: This works, but the encoded string can be much longer than needed. That's because by converting numbers to strings, you're only using a tiny fraction of the input space, but b64encode doesn't know about that (e.g.it doesn't know there'll never be a letter). I think it's better to use the 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.
This is the actual answer: 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)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.