Java Integer Create toInteger(byte[] bytes, int index)

Here you can find the source of toInteger(byte[] bytes, int index)

Description

Convert the necessary number of bytes starting at the given index to an int.

License

Apache License

Parameter

Parameter Description
bytes a parameter
index a parameter

Declaration

public static int toInteger(byte[] bytes, int index) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /** //  w  ww  . jav  a  2 s  .  com
     * Convert the necessary number of bytes starting at the given index
     * to an int.
     * 
     * @param bytes
     * @param index
     * @return
     */
    public static int toInteger(byte[] bytes, int index) {
        int val = 0;
        int typeBytes = Integer.SIZE / Byte.SIZE;
        checkBounds(bytes, index, typeBytes);
        for (int i = 0; i < typeBytes; i++) {
            int b = bytes[index++];
            b = (b < 0) ? b + 256 : b;
            int shiftBits = Byte.SIZE * (typeBytes - i - 1);
            val += (b << shiftBits);
        }
        return val;
    }

    /**
     * Utility method used to bounds check the byte array
      * and requested offset & length values.
      * 
     * @param bytes
     * @param offset
     * @param length
     */
    public static void checkBounds(byte[] bytes, int offset, int length) {
        if (length < 0)
            throw new IndexOutOfBoundsException("Index out of range: " + length);
        if (offset < 0)
            throw new IndexOutOfBoundsException("Index out of range: " + offset);
        if (offset > bytes.length - length)
            throw new IndexOutOfBoundsException("Index out of range: " + (offset + length));
    }
}

Related

  1. toInteger(byte b1, byte b2, byte b3, byte b4)
  2. toInteger(byte[] b)
  3. toInteger(byte[] b)
  4. toInteger(byte[] bytes)
  5. toInteger(byte[] bytes)
  6. toInteger(byte[] input)
  7. toInteger(E val)
  8. toInteger(final byte[] data)
  9. toInteger(final Double value)