Convert byte[] to base64 and ASCII in Python

This honestly should be all that you need: https://docs.python.org/3.1/library/base64.html

In this example you can see where they convert bytes to base64 and decode it back to bytes again:

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

You may need to first take your array and turn it into a string with join, like this:

>>> my_joined_string_of_bytes = "".join(["my", "cool", "strings", "of", "bytes"])

Let me know if you need anything else. Thanks!


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.encode('utf-8'))
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.

Tags:

Python