Skip to content

Instantly share code, notes, and snippets.

@skypanther
Created July 26, 2017 13:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skypanther/a337e244f8e5f8f5ac924f6d1f3077d1 to your computer and use it in GitHub Desktop.
Save skypanther/a337e244f8e5f8f5ac924f6d1f3077d1 to your computer and use it in GitHub Desktop.
Titanium, alternative base64encode function; not the author, sorry I don't recall the original source for this; also untested in recent Ti versions
// alternative to built-in base64 encode function, which has outstanding bugs
// alternatively, use:
// String(Ti.Utils.base64encode(theBlob)).replace(/(\r\n|\n|\r)/gm,"");
function Base64EncodeAscii(str) {
if (/([^\u0000-\u00ff])/.test(str)) {
throw 'String must be ASCII';
}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1,
o2,
o3,
bits,
h1,
h2,
h3,
h4,
e = [],
pad = '',
c;
c = str.length % 3;
// pad string to length of multiple of 3
if (c > 0) {
while (c++ < 3) {
pad += '=';
str += '\0';
}
}
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for (c = 0; c < str.length; c += 3) { // pack three octets into four hexets
o1 = str.charCodeAt(c);
o2 = str.charCodeAt(c + 1);
o3 = str.charCodeAt(c + 2);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c / 3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
str = e.join('');
// use Array.join() for better performance than repeated string appends
// replace 'A's from padded nulls with '='s
str = str.slice(0, str.length - pad.length) + pad;
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment