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.
Answer from Maurice Meyer on Stack OverflowThe 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!
python - How to convert a Base64 file to bytes? - Stack Overflow
code golf - Convert a bytes array to base64 - Code Golf Stack Exchange
Why does base64.b64encode() in python3 return a bytes object, not a string object? Isn't converting to string the point?
From hex to base64 without encoding
What works for me is to change the b64encode line to:
myObj = [base64.b64encode(data).decode('ascii')]
This is explained in https://stackoverflow.com/a/42776711 :
base64 has been intentionally classified as a binary transform.... It was a design decision in Python 3 to force the separation of bytes and text and prohibit implicit transformations.
The accepted answer doesn't work for me (Python 3.9) and gives the error:
Traceback (most recent call last):
File "/tmp/x.py", line 4, in <module>
myObj = [base64.b64encode(data)]
File "/usr/lib64/python3.9/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
Try
data = b'foo'.decode('UTF-8')
instead of
data = b'foo'
to convert it into a string.
just two lines could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just an example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.
you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
JavaScript, 177 187 198 characters
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87)))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}
For adding linebreaks, \r\n, after each 76th character, add 23 characters to the code:
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}
Demo code:
var encode = function(d,a,e,b,c,f){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c};
//OP test case
console.log(encode([99, 97, 102, 195, 169])); // outputs "Y2Fmw6k=".
//Quote from Hobbes' Leviathan:
console.log(
encode(
("Man is distinguished, not only by his reason, but by this singular passion from " +
"other animals, which is a lust of the mind, that by a perseverance of delight " +
"in the continued and indefatigable generation of knowledge, exceeds the short " +
"vehemence of any carnal pleasure.")
.split('').map(function(i){return i.charCodeAt(0)})
)
);
C, 276 bytes
Quite a bump of this thread but I came up with this question myself a few days ago, then found out about code golfing, then found out about this thread.
Takes the 0-255 int array as first console arg (just a string). Uses K&R C style function parameter declaration and RFC 2045 encoding (except with no 76-character limit).
#define u(_)unsigned _:6;
b(i,j){putchar(j?i>61?43+i%2*4:i+65+6*(i>25)-75*(i>51):61);}i=-3;main(o,c)char**c;{char*s=c[1];for(;(i+=3)<strlen(s);){union{struct{u(a)u(b)u(c)u(d)};char s[3];}a;a.s[2]=s[i];a.s[1]=s[i+1];*a.s=s[i+2];b(a.d);b(a.c);b(a.b,a.s[1]);b(a.a,a.s[1]**a.s);}}
More 'readable' version of the algorithm (it was originally more clear but I started obfusc-golfing it right away so it turned out like this):
#include <stdio.h>
#include <string.h>
void b64_char(int i) {
putchar(i>61?43+i%2*4:i+65+6*(i>25)-75*(i>51));
}
int i=-3;
int main(int argc, char* argv[]) {
char* str = argv[1];
for (;(i+=3)<strlen(str);) {
union {
struct {unsigned a:6; unsigned b:6; unsigned c:6; unsigned d:6;};
char s[3];
} a;
a.s[2]=str[i];
a.s[1]=str[i+1];
a.s[0]=str[i+2];
b64_char(a.d);
b64_char(a.c);
a.s[1]?b64_char(a.b):putchar(61);
a.s[0]&&a.s[1]?b64_char(a.a):putchar(61);
}
return 0;
}
Defining the Base64 symbol table like that saved me a bunch of bytes. Basically taking advantage of the consecutiveness of letters in ASCII.
Also, architecture dependent since it only works on little endian machines, and fails non-deterministically when the unpassed parameter for the function b(2) happens to be 0.
This would have been a lot shorter on a big endian machine.
Can anybody shorten this any further?