From 542b242c41b6b37f410e4f317b33ea88eabd4960 Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Fri, 15 Apr 2016 17:13:36 +0200 Subject: [PATCH] Added get bits function for arrays --- src/zutil/ByteUtil.java | 28 +++++++++++++++++++++++++++- test/zutil/ByteUtilTest.java | 13 +++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/zutil/ByteUtil.java b/src/zutil/ByteUtil.java index 82c063f..ce40587 100755 --- a/src/zutil/ByteUtil.java +++ b/src/zutil/ByteUtil.java @@ -57,7 +57,18 @@ public class ByteUtil { } /** - * Creates a new sub byte from index and with a length + * Creates a new sub byte from index and with the given length length + * + * @param data is the byte data + * @param length is the length of bits to return, valid values 1-8 + * @return a new byte containing a sub byte defined by the index and length + */ + public static byte getBits(byte data, int length){ + return getBits(data, 0, length); + } + + /** + * Creates a new sub byte from index and with the given length length * * @param data is the byte data * @param index is the bit index, valid values 0-7 @@ -69,6 +80,21 @@ public class ByteUtil { return ret; } + /** + * Creates a new sub byte array with only the given length of bits from the data array. + * + * @param data is the byte data array + * @param length is the length of bits to return + * @return a new byte array of te given length containing the given data. + */ + public static byte[] getBits(byte[] data, int length){ + byte[] dest = new byte[(int) Math.ceil(length/8.0)]; + System.arraycopy(data, 0, dest, 0, Math.min(data.length, dest.length)); + if(length % 8 != 0) + dest[dest.length-1] = getBits(dest[dest.length-1], length % 8); + return dest; + } + /** * Returns a byte bitmask * diff --git a/test/zutil/ByteUtilTest.java b/test/zutil/ByteUtilTest.java index 96a560b..5daf888 100755 --- a/test/zutil/ByteUtilTest.java +++ b/test/zutil/ByteUtilTest.java @@ -26,6 +26,7 @@ package zutil; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -45,4 +46,16 @@ public class ByteUtilTest { assertEquals((byte)0xFF, ByteUtil.getShiftedBits((byte)0b1111_1111, 7, 8)); } + + + @Test + public void getBitsArray(){ + assertArrayEquals(new byte[]{}, ByteUtil.getBits(new byte[]{0x00}, 0)); + assertArrayEquals(new byte[]{0x00}, ByteUtil.getBits(new byte[]{}, 1)); + assertArrayEquals(new byte[]{0x00,0x00,0x00,0x00}, ByteUtil.getBits(new byte[]{0x00}, 32)); + assertArrayEquals(new byte[]{0x00}, ByteUtil.getBits(new byte[]{0x00,0x10}, 1)); + assertArrayEquals(new byte[]{0x00}, ByteUtil.getBits(new byte[]{0x00,0x10}, 8)); + assertArrayEquals(new byte[]{0x00,0x01}, ByteUtil.getBits(new byte[]{0x00,0x01}, 9)); + assertArrayEquals(new byte[]{0x00,0x01}, ByteUtil.getBits(new byte[]{0x00,0x11}, 9)); + } }