Android ByteBuffer to Byte Array Convert toBytes(ByteBuffer buffer, int startPosition)

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

Description

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

License

Apache License

Parameter

Parameter Description
buffer copy from here
startPosition put buffer.get(startPosition) into byte[0]

Return

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

Declaration

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

Method Source Code

//package com.java2s;
/*/*from   w w  w. jav  a2s  .c  om*/
 * 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;
    }
}