Java ByteBuffer to Int readInt(ByteBuffer buf, int pos)

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

Description

Reads a specific integer byte value (4 bytes) 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 int value read

Declaration

public static int readInt(ByteBuffer buf, int pos) 

Method Source Code

//package com.java2s;
/*// w w  w  .  j av  a 2 s .  com
 * 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 integer byte value (4 bytes) 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 int value read
     */
    public static int readInt(byte[] buf, int pos) {
        checkBoundary(buf, pos, 4);
        return (((buf[pos++] & 0xff) << 24) | ((buf[pos++] & 0xff) << 16)
                | ((buf[pos++] & 0xff) << 8) | (buf[pos] & 0xff));
    }

    /**
     * Reads a specific integer byte value (4 bytes) 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 int value read
     */
    public static int readInt(ByteBuffer buf, int pos) {
        return (((buf.get(pos) & 0xff) << 24)
                | ((buf.get(pos + 1) & 0xff) << 16)
                | ((buf.get(pos + 2) & 0xff) << 8) | (buf.get(pos + 3) & 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. getUShort(ByteBuffer buffer)
  2. getUShort(ByteBuffer buffer)
  3. getUShort(java.nio.ByteBuffer buffer)
  4. readInt(ByteBuffer buf)
  5. readInt(ByteBuffer buf, int length)
  6. readInt(ByteBuffer buffer)
  7. readInt(ByteBuffer buffer)
  8. readInt(ReadableByteChannel channel, ByteBuffer buffer)
  9. readInt16(ByteBuffer bb)