Last active
December 21, 2015 13:59
-
-
Save itang/6316905 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
| public static List<byte[]> grouped(final byte[] input, final int length) { | |
| if (length <= 0) { | |
| throw new IllegalArgumentException("length must gt 0"); | |
| } | |
| List<byte[]> ret = new ArrayList<byte[]>(); | |
| int r = input.length / length; | |
| int from = 0; | |
| int to = 0; | |
| for (int i = 0; i < r; i++) { | |
| from = i * length; | |
| to = from + length; | |
| ret.add(Arrays.copyOfRange(input, from, to)); | |
| } | |
| int y = input.length % length; | |
| if (y != 0) { | |
| from = to; | |
| to = input.length; | |
| ret.add(Arrays.copyOfRange(input, from, to)); | |
| } | |
| return ret; | |
| } | |
| public static byte[] concat(final List<byte[]> bytes) { | |
| int length = 0; | |
| for (byte[] b : bytes) { | |
| length += b.length; | |
| } | |
| byte[] ret = new byte[length]; | |
| int destPos = 0; | |
| for (byte[] b : bytes) { | |
| System.arraycopy(b, 0, ret, destPos, b.length); | |
| destPos += b.length; | |
| } | |
| return ret; | |
| } |
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
| @Test | |
| public void grouped() { | |
| byte[] input = { 1, 2, 3, 4, 5 }; | |
| for (int i = 1; i < input.length * 2; i++) { | |
| printlnGrouped(input, 1); | |
| assertTrue(Arrays.equals(input, Crypto.Util.concat(Crypto.Util.grouped(input, i)))); | |
| } | |
| } | |
| private void printlnGrouped(byte[] input, int len) { | |
| System.out.print(String.format("grouped(%s,%d) => ", Arrays.toString(input), len)); | |
| List<byte[]> bytes = Crypto.Util.grouped(input, len); | |
| for (byte[] b : bytes) { | |
| System.out.print(", "); | |
| System.out.print(Arrays.toString(b)); | |
| } | |
| println(" | " + Arrays.toString(Crypto.Util.concat(bytes))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment