Slicing byte arrays in Java

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

You can use the Arrays.copyOfRange method. For example:

// slice from index 5 to index 9
byte[] slice = Arrays.copyOfRange(myArray, 5, 10);

Solution 2 - Java

The ByteBuffer you created is being backed by that array. When you call slice() you effectively receive a specific view of that data:

>Creates a new byte buffer whose content is a shared subsequence of this buffer's content.

So calling array() on that returned ByteBuffer returns the backing array in its entirety.

To extract all the bytes from that view, you could do:

byte[] bytes = new byte[slicedBuf.remaining()];
slicedBuf.read(bytes);

The bytes from that view would be copied to the new array.

Edit to add from comments below: It's worth noting that if all you're interested in doing is copying bytes from one byte[] to another byte[], there's no reason to use a ByteBuffer; simply copy the bytes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEricView Question on Stackoverflow
Solution 1 - JavaJoniView Answer on Stackoverflow
Solution 2 - JavaBrian RoachView Answer on Stackoverflow