Java Byte Array to Endian bytesToInt32(byte[] buffer, int byteOffset, boolean bigEndian)

Here you can find the source of bytesToInt32(byte[] buffer, int byteOffset, boolean bigEndian)

Description

Converts a 4 successive bytes starting at byteOffset in buffer to a signed 32bit integer sample.

License

Open Source License

Declaration

public static int bytesToInt32(byte[] buffer, int byteOffset,
        boolean bigEndian) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   ww w  . j a v  a 2s . c o m
     * Converts a 4 successive bytes starting at <code>byteOffset</code> in
     * <code>buffer</code> to a signed 32bit integer sample.
     * <p>
     * For little endian, buffer[byteOffset] is interpreted as lowest byte,
     * whereas it is interpreted as highest byte in big endian.
     * <p> This is a reference function.
     */
    public static int bytesToInt32(byte[] buffer, int byteOffset,
            boolean bigEndian) {
        return bigEndian ? ((buffer[byteOffset] << 24) // let Java handle sign-bit
                | ((buffer[byteOffset + 1] & 0xFF) << 16) // inhibit sign-bit handling
                | ((buffer[byteOffset + 2] & 0xFF) << 8) // inhibit sign-bit handling
        | (buffer[byteOffset + 3] & 0xFF))
                : ((buffer[byteOffset + 3] << 24) // let Java handle sign-bit
                        | ((buffer[byteOffset + 2] & 0xFF) << 16) // inhibit sign-bit handling
                        | ((buffer[byteOffset + 1] & 0xFF) << 8) // inhibit sign-bit handling
                | (buffer[byteOffset] & 0xFF));
    }
}

Related

  1. BytesToDouble_With_Little_Endian(byte[] bytes)
  2. bytesToInt(byte[] bytes, int offset, int length, boolean littleEndian)
  3. bytesToIntBigEndian(byte[] buf)
  4. bytesToIntLE(byte[] bytes, int offset, int length)
  5. bytesToLongLittleEndian(final byte[] vals, final int from)
  6. bytesToNumberLittleEndian(byte[] buffer, int start, int length)