Java Byte Array to Int bytesToInt(byte[] bytes, int offset)

Here you can find the source of bytesToInt(byte[] bytes, int offset)

Description

32 bit.

License

Apache License

Parameter

Parameter Description
bytes a parameter
offset a parameter

Declaration

public static int bytesToInt(byte[] bytes, int offset) 

Method Source Code

//package com.java2s;
/*//from  w w w  . j  a v a2s.c  o m
 * 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 {
    /**
     * 32 bit.
     * 
     * @param bytes
     * @return
     */
    public static int bytesToInt(byte[] bytes) {
        return bytesToInt(bytes, 0);
    }

    /**
     * 32 bit.
     * 
     * @param bytes
     * @param offset
     * @return
     */
    public static int bytesToInt(byte[] bytes, int offset) {
        // 
        int result = 0x00000000;

        int length;
        if (bytes.length - offset < 4) // maximum byte size for int data type
                                       // is 4
            length = bytes.length - offset;
        else
            length = 4;

        int end = offset + length;
        for (int i = 0; i < length; i++) {
            result |= (bytes[end - i - 1] & 0xff) << (8 * i); // TODO uudashr: CHECK FOR IMPROVEMENT
        }
        return result;
    }
}

Related

  1. bytesToInt(byte[] bytes)
  2. bytesToInt(byte[] bytes)
  3. bytesToInt(byte[] bytes)
  4. bytesToInt(byte[] bytes)
  5. bytesToInt(byte[] bytes, int bitOffset, int bitCount)
  6. bytesToInt(byte[] bytes, int offset, int length)
  7. bytesToInt(byte[] bytes, int start)
  8. bytesToInt(byte[] bytesSource)
  9. bytesToInt(byte[] data)