Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert byte array to base64 string
var i2a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'];
exports.base64_encode = function(s) {
var length = s.length;
var groupCount = Math.floor(length / 3);
var remaining = length - 3 * groupCount;
var result = "";
var idx = 0;
for (var i = 0; i < groupCount; i++) {
var b0 = s[idx++] & 0xff;
var b1 = s[idx++] & 0xff;
var b2 = s[idx++] & 0xff;
result += (i2a[b0 >> 2]);
result += (i2a[(b0 << 4) & 0x3f | (b1 >> 4)]);
result += (i2a[(b1 << 2) & 0x3f | (b2 >> 6)]);
result += (i2a[b2 & 0x3f]);
}
if (remaining == 0) {
} else if (remaining == 1) {
var b0 = s[idx++] & 0xff;
result += (i2a[b0 >> 2] );
result += (i2a[(b0 << 4) & 0x3f] );
result += ("==" );
} else if (remaining == 2) {
var b0 = s[idx++] & 0xff;
var b1 = s[idx++] & 0xff;
result += (i2a[b0 >> 2] );
result += (i2a[(b0 << 4) & 0x3f | (b1 >> 4)]);
result += (i2a[(b1 << 2) & 0x3f] );
result += ('=');
} else {
throw "never happen";
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.