convert bytes to int. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

convert bytes to int.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toInt(bytes));
    }/*from w  w  w.  j  av  a2s .c  o m*/

    /** nbr of bytes. */
    private static final int BYTE_LENGTH = 4;
    /** nbr of shift positions. */
    private static final int BYTE_SHIFT = 8;

    /**
     * convert bytes to int.
     * 
     * @param bytes
     *            bytes to convert
     * @return int given bytes as an int
     */
    public static int toInt(byte[] bytes) {
        int result = 0;
        for (int i = 0; i < BYTE_LENGTH; i++) {
            result = (result << BYTE_SHIFT) - Byte.MIN_VALUE + bytes[i];
        }
        return result;
    }
}

Related Tutorials