divide array into smaller parts

Viewed 33471

I would like to divide a large byte array into smaller chunks (say 64 bytes). Please help me with this.

8 Answers

Damian Vash's first method (the one using Arrays.copyOfRange()) adds zeros to the end of the last chunk if the input is not exactly a multiple of chunksize.

You might want to use this instead:

public static List<byte[]> divideArray(byte[] source, int chunksize) {

    List<byte[]> result = new ArrayList<byte[]>();
    int start = 0;
    while (start < source.length) {
        int end = Math.min(source.length, start + chunksize);
        result.add(Arrays.copyOfRange(source, start, end));
        start += chunksize;
    }

    return result;
}

and in case it's useful, the same thing using ArrayList's:

  public static List<List<String>> divideList(List<String> source, int chunksize) {
    List<List<String>> result = new ArrayList<List<String>>();
    int start = 0;
    while (start < source.size()) {
      int end = Math.min(source.size(), start + chunksize);
      result.add(source.subList(start, end));
      start += chunksize;
    }
    return result;
  }

This is another possible way of using Arrays.copyOfRange to divide a byte array in chunks (splitting the "data" in blockSize chunks):

byte[] data = { 2, 3, 5, 7, 8, 9, 11, 12, 13 };
// Block size in bytes (default: 64k)
int blockSize = 64 * 1024;
int blockCount = (data.length + blockSize - 1) / blockSize;

byte[] range;

try {
  
    for (int i = 1; i < blockCount; i++) {
        int idx = (i - 1) * blockSize;
        range = Arrays.copyOfRange(data, idx, idx + blockSize);
        System.out.println("Chunk " + i + ": " Arrays.toString(range));
    }

} finally {
    
    // Last chunk
    int end = -1;
    if (data.length % blockSize == 0) {
            end = data.length;
    } else {
            end = data.length % blockSize + blockSize * (blockCount - 1);
    }
        
    range = Arrays.copyOfRange(data, (blockCount - 1) * blockSize, end);

    System.out.println("Chunk " + blockCount + ": " Arrays.toString(range));
}
Related