Java ByteBuffer to Byte readByte(ByteBuffer buf, int pos)

Here you can find the source of readByte(ByteBuffer buf, int pos)

Description

Reads a specific byte value from the input byte buffer at the given offset.

License

Apache License

Parameter

Parameter Description
buf input byte buffer
pos offset into the byte buffer to read

Return

the byte value read

Declaration

public static byte readByte(ByteBuffer buf, int pos) 

Method Source Code

//package com.java2s;
/*/*from  www  .  j  a v  a  2s.c o  m*/
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the ?License??). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Reads a specific byte value from the input byte array at the given offset.
     *
     * @param buf input byte array
     * @param pos offset into the byte buffer to read
     * @return the byte value read
     */
    public static byte readByte(byte[] buf, int pos) {
        checkBoundary(buf, pos, 1);
        return (byte) (buf[pos] & 0xff);
    }

    /**
     * Reads a specific byte value from the input byte buffer at the given offset.
     *
     * @param buf input byte buffer
     * @param pos offset into the byte buffer to read
     * @return the byte value read
     */
    public static byte readByte(ByteBuffer buf, int pos) {
        return (byte) (buf.get(pos) & 0xff);
    }

    /**
     * Ensures that the given buffer contains at least the given number of bytes after the given
     * offset.
     *
     * @param buf input byte array
     * @param pos position in the byte array to start writing
     * @param len length of data to write from the given position
     */
    private static void checkBoundary(byte[] buf, int pos, int len) {
        if (pos + len > buf.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
    }
}

Related

  1. readByte(ByteBuffer buf, int i)