Skip to content

Instantly share code, notes, and snippets.

@scizzr
Forked from EmilHernvall/Base64.java
Last active December 18, 2015 00:19
Show Gist options
  • Save scizzr/5695546 to your computer and use it in GitHub Desktop.
Save scizzr/5695546 to your computer and use it in GitHub Desktop.
public class Base64
{
public static String encode(byte[] data)
{
char[] tbl = {
'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','+','/' };
StringBuilder buffer = new StringBuilder();
int pad = 0;
for (int i = 0; i < data.length; i += 3) {
int b = ((data[i] & 0xFF) << 16) & 0xFFFFFF;
if (i + 1 < data.length) {
b |= (data[i+1] & 0xFF) << 8;
} else {
pad++;
}
if (i + 2 < data.length) {
b |= (data[i+2] & 0xFF);
} else {
pad++;
}
// why the fuck does this have to be here?
if (i % 57 == 0 && i > 0) {
buffer.append("\n");
}
while ((b & 0xFFFFFF) != 0) {
int c = (b & 0xFC0000) >> 18;
buffer.append(tbl[c]);
b <<= 6;
}
}
for (int j = 0; j < pad; j++) {
buffer.append("=");
}
return buffer.toString();
}
}
@Edgarins29
Copy link

Hi,
I tried using decoding part of code, but couldn't get working decode, so it decodes:
String stru = "c8SBbHM=";
It returns "sÄ�ls", but it should return "sāls", it is probably some problem with UTF-8.

I also tried to incorporate some conversion from bytes to String but still I'm stuck.

Encoding part is working fine with UTF-8, thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment