Decode base64 data as array in Python
Posted
by
skerit
on Stack Overflow
See other posts from Stack Overflow
or by skerit
Published on 2010-12-30T14:46:09Z
Indexed on
2010/12/30
14:54 UTC
Read the original article
Hit count: 265
I'm using this handy Javascript function to decode a base64 string and get an array in return.
This is the string:
base64_decode_array('6gAAAOsAAADsAAAACAEAAAkBAAAKAQAAJgEAACcBAAAoAQAA')
This is what's returned:
234,0,0,0,235,0,0,0,236,0,0,0,8,1,0,0,9,1,0,0,10,1,0,0,38,1,0,0,39,1,0,0,40,1,0,0
The problem is I don't really understand the javascript function:
var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split("");
var base64inv = {};
for (var i = 0; i < base64chars.length; i++) {
base64inv[base64chars[i]] = i;
}
function base64_decode_array (s)
{
// remove/ignore any characters not in the base64 characters list
// or the pad character -- particularly newlines
s = s.replace(new RegExp('[^'+base64chars.join("")+'=]', 'g'), "");
// replace any incoming padding with a zero pad (the 'A' character is zero)
var p = (s.charAt(s.length-1) == '=' ?
(s.charAt(s.length-2) == '=' ? 'AA' : 'A') : "");
var r = [];
s = s.substr(0, s.length - p.length) + p;
// increment over the length of this encrypted string, four characters at a time
for (var c = 0; c < s.length; c += 4) {
// each of these four characters represents a 6-bit index in the base64 characters list
// which, when concatenated, will give the 24-bit number for the original 3 characters
var n = (base64inv[s.charAt(c)] << 18) + (base64inv[s.charAt(c+1)] << 12) +
(base64inv[s.charAt(c+2)] << 6) + base64inv[s.charAt(c+3)];
// split the 24-bit number into the original three 8-bit (ASCII) characters
r.push((n >>> 16) & 255);
r.push((n >>> 8) & 255);
r.push(n & 255);
}
// remove any zero pad that was added to make this a multiple of 24 bits
return r;
}
What's the function of those "<<<" and ">>>" characters. Or is there a function like this for Python?
© Stack Overflow or respective owner