Java Convert via ByteBuffer toIntFromByteArray(byte[] byteArray)

Here you can find the source of toIntFromByteArray(byte[] byteArray)

Description

Returns an integer value out of a byte array.

License

Open Source License

Parameter

Parameter Description
byteArray The byte array to be converted into its decimal representation

Return

The integer value representing the byte array

Declaration

public static int toIntFromByteArray(byte[] byteArray) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *  Copyright (c) 2016 Dr.-Ing. Marc M?ltin.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors://w w w  . j a va  2s  .  c  om
 *    Dr.-Ing. Marc M?ltin - initial API and implementation and initial documentation
 *******************************************************************************/

import java.nio.ByteBuffer;

public class Main {
    /**
     * Returns an integer value out of a byte array. 
     * 
     * @param byteArray The byte array to be converted into its decimal representation
     * @return The integer value representing the byte array
     */
    public static int toIntFromByteArray(byte[] byteArray) {
        // Allocating a byte buffer holding 4 bytes for the int value
        ByteBuffer bb = ByteBuffer.allocate(4);

        /*
         * The given byte array might hold less than 4 bytes, e.g. the SECC port of the SECC Discovery
         * Response only holds 2 bytes. Thus, we must account for this and guarantee the Big Endian 
         * byte order.
         */
        bb.position(4 - byteArray.length);
        bb.put(byteArray);

        // Setting the current position to 0, otherwise getInt() would throw a BufferUnderflowException
        bb.position(0);

        return bb.getInt();
    }
}

Related

  1. toIntArray(byte[] byteArray)
  2. toIntArray(byte[] byteArray)
  3. toIntArray(final byte[] byteArray)
  4. toIntArray(float[] floatArray)
  5. toIntBuffer(int[] array)
  6. toLittleEndian(int value)
  7. toLMBCS(final String value)
  8. toLong(byte data[])
  9. toLong(byte[] array)