Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to base64 and ASCII in Python

Tags:

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

like image 548
Light Avatar asked May 11 '17 16:05

Light


People also ask

How do I convert to Base 64 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.

What is b64encode Python?

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.

Is Base64 an ASCII?

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.


2 Answers

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.

like image 128
Maurice Meyer Avatar answered Sep 19 '22 01:09

Maurice Meyer


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!

like image 27
gman Avatar answered Sep 18 '22 01:09

gman