Java ByteBuffer to Int Array readIntArray(ByteBuffer in)

Here you can find the source of readIntArray(ByteBuffer in)

Description

read Int Array

License

Apache License

Declaration

public static int[] readIntArray(ByteBuffer in) 

Method Source Code

//package com.java2s;
/*//w ww. j  a v a 2 s . c o  m
 * 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 {
    public static int[] readIntArray(ByteBuffer in) {
        int len = readVInt(in);
        if (len < 0)
            return null;
        int[] array = new int[len];

        for (int i = 0; i < len; ++i) {
            array[i] = readVInt(in);
        }
        return array;
    }

    public static int readVInt(ByteBuffer in) {
        long n = readVLong(in);
        if ((n > Integer.MAX_VALUE) || (n < Integer.MIN_VALUE)) {
            throw new IllegalArgumentException(
                    "value too long to fit in integer");
        }
        return (int) n;
    }

    public static long readVLong(ByteBuffer in) {
        byte firstByte = in.get();
        int len = decodeVIntSize(firstByte);
        if (len == 1) {
            return firstByte;
        }
        long i = 0;
        for (int idx = 0; idx < len - 1; idx++) {
            byte b = in.get();
            i = i << 8;
            i = i | (b & 0xFF);
        }
        return (isNegativeVInt(firstByte) ? (i ^ -1L) : i);
    }

    private static int decodeVIntSize(byte value) {
        if (value >= -112) {
            return 1;
        } else if (value < -120) {
            return -119 - value;
        }
        return -111 - value;
    }

    private static boolean isNegativeVInt(byte value) {
        return value < -120 || (value >= -112 && value < 0);
    }
}

Related

  1. getIntFromBack(ByteBuffer bb)
  2. getIntFromByteBuffer(ByteBuffer data)
  3. getIntWithChecksum(ByteBuffer buffer, Adler32 checksum)
  4. readIntArray(ByteBuffer bb)
  5. readIntArray(ByteBuffer buf)
  6. readIntegerArray(ByteBuffer bb, int length)