Created
February 6, 2018 19:24
-
-
Save sonOfRa/c35a1f0dbf77f2380a60335999a5be95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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