Java Convert via ByteBuffer toInt(byte[] value)

Here you can find the source of toInt(byte[] value)

Description

Convert the first 4 bytes of an array to a big endian int.

License

Apache License

Parameter

Parameter Description
value The byte array.

Return

The int represented by the array.

Declaration

public static int toInt(byte[] value) 

Method Source Code


//package com.java2s;
/*//from  w  ww .j a  v  a2  s .co  m
 * Licensed to the Warcraft4J Project under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The Warcraft4J Project licenses
 * this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**
     * Convert the first 4 bytes of an array to a big endian int.
     *
     * @param value The byte array.
     *
     * @return The int represented by the array.
     */
    public static int toInt(byte[] value) {
        if (value == null) {
            return 0;
        }
        int val = 0;
        if (value.length >= 1) {
            val |= ((value[0] & 0xFF) << 24);
        }
        if (value.length >= 2) {
            val |= ((value[1] & 0xFF) << 16);
        }
        if (value.length >= 3) {
            val |= ((value[2] & 0xFF) << 8);
        }
        if (value.length >= 4) {
            val |= ((value[3] & 0xFF));
        }
        return val;
    }

    /**
     * Convert the first 4 bytes of an array to a int.
     *
     * @param value     The byte array.
     * @param byteOrder The byte order of the int.
     *
     * @return The int represented by the array.
     */
    public static int toInt(byte[] value, ByteOrder byteOrder) {
        return ByteBuffer.wrap(value).order(byteOrder).getInt();
    }
}

Related

  1. toHex(byte[] bytes)
  2. toHexBytes(byte[] bytes)
  3. toHexString(Number n)
  4. toInt(byte[] bytes)
  5. toInt(byte[] data)
  6. toInt(final byte lowOrderByte, final byte highOrderByte)
  7. toInt(InetAddress address)
  8. toIntArray(byte[] byteArray)
  9. toIntArray(byte[] byteArray)