How do I to convert and array of byte to base64 string and/or ASCII.
I can do this easily in C#, but can't seem to do this in Python
To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.
b64encode(s, altchars=None) Encode the bytes-like object s using Base64 and return the encoded bytes . Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and / characters.
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With