Java ByteBuffer to Byte Array toBytes(ByteBuffer buffer, int offset, int length)

Here you can find the source of toBytes(ByteBuffer buffer, int offset, int length)

Description

Copy the given number of bytes from specified offset into a new byte[]

License

Apache License

Parameter

Parameter Description
buffer a parameter
offset a parameter
length a parameter

Return

a new byte[] containing the bytes in the specified range

Declaration

public static byte[] toBytes(ByteBuffer buffer, int offset, int length) 

Method Source Code

//package com.java2s;
/*/*ww  w . j  av a 2 s . com*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Copy the bytes from position to limit into a new byte[] of the exact length and sets the
     * position and limit back to their original values (though not thread safe).
     * @param buffer copy from here
     * @param startPosition put buffer.get(startPosition) into byte[0]
     * @return a new byte[] containing the bytes in the specified range
     */
    public static byte[] toBytes(ByteBuffer buffer, int startPosition) {
        int originalPosition = buffer.position();
        byte[] output = new byte[buffer.limit() - startPosition];
        buffer.position(startPosition);
        buffer.get(output);
        buffer.position(originalPosition);
        return output;
    }

    /**
     * Copy the given number of bytes from specified offset into a new byte[]
     * @param buffer
     * @param offset
     * @param length
     * @return a new byte[] containing the bytes in the specified range
     */
    public static byte[] toBytes(ByteBuffer buffer, int offset, int length) {
        byte[] output = new byte[length];
        for (int i = 0; i < length; i++) {
            output[i] = buffer.get(offset + i);
        }
        return output;
    }
}

Related

  1. toByteArray(ByteBuffer bytes)
  2. toByteArrayByByteBuffer(int value)
  3. toBytes(ByteBuffer buff)
  4. toBytes(ByteBuffer buffer)
  5. toBytes(ByteBuffer buffer)
  6. toBytes(ByteBuffer buffer, int startPosition)
  7. toBytes(ByteBuffer value)
  8. toBytes(final ByteBuffer bb)