Skip to content

Instantly share code, notes, and snippets.

@sonOfRa
Created February 6, 2018 19:24
Show Gist options
  • Select an option

  • Save sonOfRa/c35a1f0dbf77f2380a60335999a5be95 to your computer and use it in GitHub Desktop.

Select an option

Save sonOfRa/c35a1f0dbf77f2380a60335999a5be95 to your computer and use it in GitHub Desktop.
/**
* Encode the given bytes as a b64 string
*
* @param data the data to encode
* @return the encoded String
*/
public static String encode(byte[] data) {
if (data.length % 3 != 0) {
throw new IllegalArgumentException("Input length not divisible by 3");
}
StringBuilder output = new StringBuilder((data.length / 3) * 4);
for (int i = 0; i < data.length; i += 3) {
byte b0 = data[i];
byte b1 = data[i + 1];
byte b2 = data[i + 2];
int w = (Byte.toUnsignedInt(b2) << 16) | (Byte.toUnsignedInt(b1) << 8) | Byte.toUnsignedInt(b0);
// WRONG
w = (b << 16) | (b1 << 8) | b0
for (int j = 0; j < 4; j++) {
output.append(B64_LOOKUP.charAt(w & 0b111111));
w >>>= 6;
}
}
return output.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment