Skip to content

Instantly share code, notes, and snippets.

@shin1ogawa
Created August 1, 2010 08:07
Show Gist options
  • Save shin1ogawa/503096 to your computer and use it in GitHub Desktop.
Save shin1ogawa/503096 to your computer and use it in GitHub Desktop.
static String byteArrayToBase64(byte[] bytes) {
int aLen = bytes.length;
int numFullGroups = aLen / 3;
int numBytesInPartialGroup = aLen - 3 * numFullGroups;
int resultLen = 4 * ((aLen + 2) / 3);
StringBuilder b = new StringBuilder(resultLen);
int inCursor = 0;
for (int i = 0; i < numFullGroups; i++) {
int byte0 = bytes[inCursor++] & 0xff;
int byte1 = bytes[inCursor++] & 0xff;
int byte2 = bytes[inCursor++] & 0xff;
b.append(intToBase64[byte0 >> 2]);
b.append(intToBase64[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
b.append(intToBase64[(byte1 << 2) & 0x3f | (byte2 >> 6)]);
b.append(intToBase64[byte2 & 0x3f]);
}
if (numBytesInPartialGroup != 0) {
int byte0 = bytes[inCursor++] & 0xff;
b.append(intToBase64[byte0 >> 2]);
if (numBytesInPartialGroup == 1) {
b.append(intToBase64[(byte0 << 4) & 0x3f]);
b.append("==");
} else {
int byte1 = bytes[inCursor++] & 0xff;
b.append(intToBase64[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
b.append(intToBase64[(byte1 << 2) & 0x3f]);
b.append('=');
}
}
return b.toString();
}
static final char intToBase64[] = { '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', '+', '/' };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment