Convert a byte array of length 4 into an int number, using little-endian notation - Java Internationalization

Java examples for Internationalization:Big Endian Little Endian

Description

Convert a byte array of length 4 into an int number, using little-endian notation

Demo Code

/*******************************************************************************
 * Copyright (c) 2008 JCrypTool Team and Contributors
 * //  ww  w.  j ava 2 s  .  co m
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] input = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toIntLittleEndian(input));
    }

    /**
     * Convert a byte array of length 4 into an int number, using little-endian notation
     * 
     * @param input - the byte array
     * @return the converted int or <tt>0</tt> if <tt>input.length != 4</tt> or the resulting integer would be negative
     */
    public static int toIntLittleEndian(byte[] input) {
        int result = 0;
        if (input.length != 4 || input[3] < 0) {
            return 0;
        }
        result ^= (input[3] & 0xff) << 24;
        result ^= (input[2] & 0xff) << 16;
        result ^= (input[1] & 0xff) << 8;
        result ^= input[0] & 0xff;
        return result;
    }
}

Related Tutorials