I'm trying to slice a byte array to prune the first part of the array. I'm using ByteBuffer but it does not behave like I would expect.
byte[] myArray = new byte[10]; ByteBuffer buf = ByteBuffer.wrap(myArray); buf.position(5); ByteBuffer slicedBuf = buf.slice(); byte[] newArray = slicedBuf.array();
I would expect the size of newArray to be 5, containing only the last portion of my ByteBuffer. Instead, the full byte array is returned. I understand that this is because the "backing buffer" is the same all along.
How can I slice to have only the desired part of the array?
EDIT: Added context
The bytes are received from network. The buffer is formed like this :
[ SHA1 hash ] [ data... lots of it ]
I already have a function that takes a byte array as a parameter and calculate the SHA1 hash. What I want is to slice the full buffer to pass only the data without the expected hash.
A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
You can simply iterate the byte array and print the byte using System. out. println() method.
You can use the Arrays.copyOfRange
method. For example:
// slice from index 5 to index 9 byte[] slice = Arrays.copyOfRange(myArray, 5, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With