Java Integer Create toInt(byte[] si)

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

Description

Convert a byte[] (most significant byte first) to the corresponding int value.

License

LGPL

Parameter

Parameter Description
si the input array

Return

The value coresponding to the byte array

Declaration

public final static int toInt(byte[] si) 

Method Source Code

//package com.java2s;
/*/*w  ww .  ja v  a  2  s  .c  o m*/
 * Copyright 2005 MBARI
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 2.1 
 * (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.gnu.org/copyleft/lesser.html
 *
 * 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.
 */

public class Main {
    /**
     * Convert a byte[] (most significant byte first) to the corresponding <b>int</b> value.
     *
     * @param  si  the input array
     * @return     The value coresponding to the byte array
     */
    public final static int toInt(byte[] si) {
        return toInt(si, false);
    }

    /**
     * Convert a byte[] to the corresponding <b>int</b> value.
     *
     * @param  si              the input array
     * @param  isReverseOrder  True if little-endian. False if big-endian (Most significant byte first)
     * @return                 The value coresponding to the byte array
     */
    public final static int toInt(byte[] si, boolean isReverseOrder) {
        int i = 0;
        if (isReverseOrder) {
            si = reverseOrder(si, 4);
        }

        int nb = si.length - 1;
        for (byte b = 0; b <= nb; b++) {
            int j;
            if (si[b] < 0) {
                si[b] = (byte) (si[b] & 0x7f);
                j = si[b];
                j |= 0x80;
            } else {
                j = si[b];
            }

            i |= j;

            if (b < nb) {
                i <<= 8;
            }
        }

        return i;
    }

    /**
     * Reverse the ordering of a byte array
     *
     * @param  si
     * @param  i
     * @return
     */
    private final static byte[] reverseOrder(byte[] si, int i) {
        byte[] is = new byte[i];
        for (byte b = 0; b <= i - 1; b++) {
            is[b] = si[i - 1 - b];
        }

        return is;
    }
}

Related

  1. toInt(byte[] input)
  2. toInt(byte[] key)
  3. toInt(byte[] n)
  4. toInt(byte[] readBuffer, int o)
  5. toInt(byte[] res)
  6. toInt(byte[] src)
  7. toInt(byte[] src)
  8. toInt(byte[] src, int srcPos)
  9. toInt(byte[] value)