Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing byte arrays in Java

Tags:

java

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.

like image 954
Eric Avatar asked Aug 21 '13 20:08

Eric


People also ask

What is byte array in Java?

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..

How do I combine byte arrays?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.


1 Answers

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

// slice from index 5 to index 9 byte[] slice = Arrays.copyOfRange(myArray, 5, 10); 
like image 55
Joni Avatar answered Sep 30 '22 03:09

Joni