Returns the integer represented by up to 4 bytes in network byte order. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Returns the integer represented by up to 4 bytes in network byte order.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] buf = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(networkByteOrderToInt(buf));
    }/*from  w  w  w  .j av  a  2s.com*/

    /**
     * Returns the integer represented by up to 4 bytes in network byte order.
     * 
     * @param buf
     * @return the integer represented by up to 4 bytes in network byte order.
     */
    public static int networkByteOrderToInt(byte[] buf) {
        return networkByteOrderToInt(buf, 0, buf.length);
    }

    /**
     * Returns the integer represented by up to 4 bytes in network byte order.
     * 
     * @param buf
     *            the buffer to read the bytes from
     * @param start
     * @param count
     * @return the integer represented by up to 4 bytes in network byte order.
     */
    public static int networkByteOrderToInt(byte[] buf, int start, int count) {
        if (count > 4) {
            throw new IllegalArgumentException(
                    "Cannot handle more than 4 bytes");
        }

        int result = 0;

        for (int i = 0; i < count; i++) {
            result <<= 8;
            result |= (buf[start + i] & 0xff);
        }

        return result;
    }
}

Related Tutorials