Java Convert via ByteBuffer toArray(final byte[] byteArray, final int sizeLimit)

Here you can find the source of toArray(final byte[] byteArray, final int sizeLimit)

Description

Splits the specified byte array into an array of ByteBuffer s, each with the specified maximum size.

License

Open Source License

Parameter

Parameter Description
byteArray The array to segment.
sizeLimit The maximum size of each byte buffer.

Return

The new array of s.

Declaration

public static ByteBuffer[] toArray(final byte[] byteArray, final int sizeLimit) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

public class Main {
    /**//  w  w  w  .  j a v  a  2  s .co  m
     * Splits the specified byte array into an array of {@link ByteBuffer}s,
     * each with the specified maximum size. This is useful, for example,
     * when trying to limit sizes to a network MTU.
     * 
     * @param byteArray The array to segment.
     * @param sizeLimit The maximum size of each byte buffer.
     * @return The new array of {@link ByteBuffer}s.
     */
    public static ByteBuffer[] toArray(final byte[] byteArray, final int sizeLimit) {
        final int numBufs = (int) Math.ceil((double) byteArray.length / (double) sizeLimit);
        final ByteBuffer[] bufs = new ByteBuffer[numBufs];

        int byteIndex = 0;
        for (int i = 0; i < numBufs; i++) {
            final int numBytes;
            final int remaining = byteArray.length - byteIndex;
            if (remaining < sizeLimit) {
                numBytes = remaining;
            } else {
                numBytes = sizeLimit;
            }
            bufs[i] = ByteBuffer.wrap(byteArray, byteIndex, numBytes);
            byteIndex += sizeLimit;
        }
        return bufs;
    }
}

Related

  1. StringToData(String conv, boolean isRe, int number)
  2. stringToIpAddress(String s)
  3. stringToLong(String offsetString)
  4. stringToLongUnknownLength(String str, int startIndex)
  5. to32BitsLongArray(byte[] data, boolean bigEndian)
  6. toArray(int value)
  7. toArray(IntBuffer src, int[] dst, int offset)
  8. toArray(long length)
  9. toASCII(String str)