Java Integer From intFrom4Bytes(byte[] bytes, int index)

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

Description

Get an unsigned integer from a 4-byte word

License

Open Source License

Parameter

Parameter Description
bytes a 4-byte array
index the index offset into the byte array to sample

Return

a 4-byte long

Declaration

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

Method Source Code

//package com.java2s;
/*//from ww  w. java  2  s  .c  om
 * Copyright (C) 2014 Jesse Caulfield 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Get an unsigned integer from a 4-byte word
     *
     * @param bytes a 4-byte array
     * @param index the index offset into the byte array to sample
     * @return a 4-byte long
     */
    public static long intFrom4Bytes(byte[] bytes, int index) {
        return intFrom4Bytes(bytes, index, false);
    }

    /**
     * Get a signed or unsigned integer from a 4-byte word.
     *
     * @param bytes  a 4-byte array
     * @param index  the index offset into the byte array to sample
     * @param signed indicator for signed/unsigned integer
     * @return a signed or unsigned integer from a 4-byte word
     */
    public static long intFrom4Bytes(byte[] bytes, int index, boolean signed) {
        int idx = index;
        long val = 0;
        /*
         * byte high = bytes[idx++]; i |= (high << 24) & 0x00000000FF000000; i |=
         * (bytes[idx++] << 16) & 0x0000000000FF0000; i |= (bytes[idx++] << 8) &
         * 0x000000000000FF00; i |= bytes[idx++] & 0x00000000000000FF; if(signed) {
         * if((high & 0x80) == 1) i*=-1; }
         */
        for (int i = 0; i < 4; i++) {
            if (i < 3) {
                val |= (((long) bytes[idx + i] & 0x000000ff) << (32 - ((i + 1) * 8)));
            } else {
                val |= ((long) bytes[idx + i] & 0x000000ff);
            }

        }
        return val;
    }
}

Related

  1. intFrom(byte a, byte b, byte c, byte d)
  2. intFrom2Bytes(byte[] bytes, int index)
  3. intFromBase64(String value)
  4. intFromBigEndainByteArray(byte[] buf, int offset, int len)
  5. intFromByte(byte byteValue)
  6. intFromByteArray(final byte[] buf, final int offset)