Convert a byte array of length 4 into an int number, using big-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 big-endian notation

Demo Code

/*******************************************************************************
 * Copyright (c) 2008 JCrypTool Team and Contributors
 * /*from  w ww . j  a  v  a 2s.  com*/
 * 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(toIntBigEndian(input));
    }

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

Related Tutorials