Java Integer Create toInt(byte[] bytes, boolean isBigEndian)

Here you can find the source of toInt(byte[] bytes, boolean isBigEndian)

Description

It will convert <= 4 bytes value to Int

License

Apache License

Parameter

Parameter Description
bytes a parameter
isBigEndian - is it Big or Little Endian

Declaration

public static int toInt(byte[] bytes, boolean isBigEndian) 

Method Source Code

//package com.java2s;
/*//from w w w .  j  a va 2  s . c o m
 * Copyright (C) 2011 Prasanta Paul, http://prasanta-paul.blogspot.com
 *
 * Licensed 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.
 */

public class Main {
    /**
     * It will convert <= 4 bytes value to Int
     * 
     * @param bytes
     * @param isBigEndian
     *            - is it Big or Little Endian
     * @return
     */
    public static int toInt(byte[] bytes, boolean isBigEndian) {
        int x = 0;
        int numOfBytes = bytes.length;

        if (numOfBytes > 4)
            numOfBytes = 4; // Can't consider more than 4 bytes

        for (int i = 0; i < numOfBytes; i++) {
            if (i == 0) {
                if (isBigEndian)
                    x = 0xFF & bytes[i]; // AND with 0xFF to ignore sign bit of
                // bytes to Int assignment
                else
                    // Little Endian
                    x = 0xFF & bytes[numOfBytes - 1];
            } else {
                if (isBigEndian)
                    x = (x << 8) | (0xFF & bytes[i]);
                else
                    x = (x << 8) | (0xFF & bytes[numOfBytes - 1 - i]);
            }
        }

        return x;
    }
}

Related

  1. toInt(byte[] bytes)
  2. toInt(byte[] bytes)
  3. toInt(byte[] bytes)
  4. toInt(byte[] bytes)
  5. toInt(byte[] bytes)
  6. toInt(byte[] bytes, int index)
  7. toInt(byte[] bytes, int offset)
  8. toInt(byte[] bytes, int offset)
  9. toInt(byte[] bytes, int offset)