Encodes an integer into up to 4 bytes in network byte order. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Encodes an integer into up to 4 bytes in network byte order.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int num = 2;
        int count = 2;
        System.out.println(java.util.Arrays.toString(intToNetworkByteOrder(
                num, count)));// w w  w  .  j  a  v  a2s  .c  om
    }

    /**
     * Encodes an integer into up to 4 bytes in network byte order.
     * 
     * @param num
     *            the int to convert to a byte array
     * @param count
     *            the number of reserved bytes for the write operation
     * @return the resulting byte array
     */
    public static byte[] intToNetworkByteOrder(int num, int count) {
        byte[] buf = new byte[count];
        intToNetworkByteOrder(num, buf, 0, count);

        return buf;
    }

    /**
     * Encodes an integer into up to 4 bytes in network byte order in the supplied buffer, 
     * starting at <code>start</code> offset and writing <code>count</code> bytes.
     * 
     * @param num the int to convert to a byte array
     * @param buf the buffer to write the bytes to
     * @param start the offset from beginning for the write operation
     * @param count the number of reserved bytes for the write operation
     * @return the resulting byte array
     */
    private static void intToNetworkByteOrder(int num, byte[] buf,
            int start, int count) {
        if (count > 4) {
            throw new IllegalArgumentException(
                    "Cannot handle more than 4 bytes");
        }

        for (int i = count - 1; i >= 0; i--) {
            buf[start + i] = (byte) (num & 0xff);
            num >>>= 8;
        }
    }
}

Related Tutorials