Java Long Number Create toLong(byte[] bytes, int index)

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

Description

Convert the necessary number of bytes starting at the given index to a long.

License

Apache License

Parameter

Parameter Description
bytes a parameter
index a parameter

Declaration

public static long toLong(byte[] bytes, int index) 

Method Source Code

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

public class Main {
    /** /*from   w ww.j  a  v a  2 s .c  o  m*/
     * Convert the necessary number of bytes starting at the given index
     * to a long.
     * 
     * @param bytes
     * @param index
     * @return
     */
    public static long toLong(byte[] bytes, int index) {
        long val = 0;
        int typeBytes = Long.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. toLong(byte[] bytes)
  2. toLong(byte[] bytes)
  3. toLong(byte[] bytes)
  4. toLong(byte[] bytes)
  5. toLong(byte[] bytes, boolean bigEndian)
  6. toLong(byte[] bytes, int index)
  7. toLong(byte[] bytes, int offset)
  8. ToLong(byte[] bytes, int offset)
  9. toLong(byte[] bytes, int offset)