Skip to content

Instantly share code, notes, and snippets.

@quard8
Created July 11, 2014 08:04
Show Gist options
  • Save quard8/c81208146290e4ab4037 to your computer and use it in GitHub Desktop.
Save quard8/c81208146290e4ab4037 to your computer and use it in GitHub Desktop.
b64.js
_.base64encode = function(string) {
var padding = '=',
chrTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function utf8Encode(str) {
var bytes = [], offset = 0, length, char;
str = encodeURI(str);
length = str.length;
while (offset < length) {
char = str[offset];
offset += 1;
if ('%' !== char) {
bytes.push(char.charCodeAt(0));
} else {
char = str[offset] + str[offset + 1];
bytes.push(parseInt(char, 16));
offset += 2;
}
}
return bytes;
}
var result = '',
bytes = utf8Encode(string),
length = bytes.length,
i;
// Convert every three bytes to 4 ascii characters.
for (i = 0; i < (length - 2); i += 3) {
result += chrTable[bytes[i] >> 2];
result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i+1] >> 4)];
result += chrTable[((bytes[i+1] & 0x0f) << 2) + (bytes[i+2] >> 6)];
result += chrTable[bytes[i+2] & 0x3f];
}
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
if (length%3) {
i = length - (length%3);
result += chrTable[bytes[i] >> 2];
if ((length%3) === 2) {
result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i+1] >> 4)];
result += chrTable[(bytes[i+1] & 0x0f) << 2];
result += padding;
} else {
result += chrTable[(bytes[i] & 0x03) << 4];
result += padding + padding;
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment