Added get bits function for arrays
This commit is contained in:
parent
ccead35ee7
commit
542b242c41
2 changed files with 40 additions and 1 deletions
|
|
@ -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
|
||||
*
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue