Java Byte Array to Int bytes2int(byte[] buf)

Here you can find the source of bytes2int(byte[] buf)

Description

Cat 4 bytes to make an int.

License

Open Source License

Parameter

Parameter Description
buf an array of at least 4 bytes, eg [0x80, 0x00, 0x00, 0x03].

Return

the resulting int, eg -2^31 + 3 or -2147483645.

Declaration

public static int bytes2int(byte[] buf) 

Method Source Code

//package com.java2s;
/*/*from   w w  w. ja  va 2 s.  c o  m*/
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */

public class Main {
    /**
     * Cat 4 bytes to make an int.
     * 
     * @param buf an array of at least 4 bytes, eg [0x80, 0x00, 0x00, 0x03].
     * @return the resulting int, eg -2^31 + 3 or -2147483645.
     */
    public static int bytes2int(byte[] buf) {
        // eg -128 == 10000000 promoted to int => 11...110000000
        // so we need & 0xff to remove added ones (except for the 1st since they're all shifted
        // away)
        return (buf[0] << 24) | ((buf[1] & 0xff) << 16) | ((buf[2] & 0xff) << 8) | (buf[3] & 0xff);
    }
}

Related

  1. bytes2int(byte value1, byte value2)
  2. bytes2Int(byte... bytes)
  3. bytes2int(byte[] ary)
  4. bytes2int(byte[] b)
  5. bytes2Int(byte[] b, int start, int len)
  6. bytes2int(byte[] bytes)
  7. bytes2Int(byte[] bytes)
  8. bytes2int(byte[] bytes)
  9. bytes2int(byte[] bytes)