Light Light - 7 months ago 47
Python Question

Convert byte[] to base64 and ASCII in Python

I am new to python and I'm quite struggling to convert and array of byte to base64 string and/or ASCII.

Tried googling stuff but can't seem to find a solution.

I can do this easily in C#, but can't seem to do this in Python 2.x/3.x

Any help is greatly appreciated.

Thanks in advance.

Answer Source

The simplest approach would be: Array to json to base64:

import json
import base64

data = [0, 1, 0, 0, 83, 116, -10]
dataStr = json.dumps(data)

base64EncodedStr = base64.b64encode(dataStr)
print(base64EncodedStr)

print('decoded', base64.b64decode(base64EncodedStr))

Prints out:

>>> WzAsIDEsIDAsIDAsIDgzLCAxMTYsIC0xMF0=
>>> ('decoded', '[0, 1, 0, 0, 83, 116, -10]')  # json.loads here !

... another option could be using bitarray module.