Skip to content

Instantly share code, notes, and snippets.

@wuyongzheng
Created September 16, 2011 09:40
Show Gist options
  • Select an option

  • Save wuyongzheng/1221685 to your computer and use it in GitHub Desktop.

Select an option

Save wuyongzheng/1221685 to your computer and use it in GitHub Desktop.
base64 encoder in Java
private static final char [] base64Map =
("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789+/").toCharArray();
private static String base64Encode (byte [] bytes)
{
if (bytes.length % 3 != 0)
bytes = Arrays.copyOf(bytes, bytes.length + 3 - bytes.length % 3);
char [] str = new char [bytes.length*4/3];
for (int i = 0; i < str.length / 4; i ++) {
int code = ((bytes[i*3] & 0xff) << 16) +
((bytes[i*3+1] & 0xff) << 8) +
(bytes[i*3+2] & 0xff);
str[i*4+0] = base64Map[(code >> 18) & 0x3f];
str[i*4+1] = base64Map[(code >> 12) & 0x3f];
str[i*4+2] = base64Map[(code >> 6) & 0x3f];
str[i*4+3] = base64Map[code & 0x3f];
}
return new String(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment