Java Byte Array Create toBytes(int n)

Here you can find the source of toBytes(int n)

Description

Returns a 4-byte array built from an int.

License

Open Source License

Declaration

public static byte[] toBytes(int n) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   ww  w  .  j a v a  2 s. c o  m
     * Returns a 4-byte array built from an int. The int's MSB is first
     * (big-endian order).
     */
    public static byte[] toBytes(int n) {
        byte[] buf = new byte[4];

        for (int i = 3; i >= 0; i--) {
            buf[i] = (byte) (n & 0xFF);
            n >>>= 8;
        }
        return buf;
    }

    /**
     * Returns a byte array built from a short array. Each short is broken
     * into 2 bytes with the short's MSB first (big-endian order).
     * <p>
     * If offset and length are omitted, the whole array is used.
     */
    public static byte[] toBytes(short[] array, int offset, int length) {
        byte[] buf = new byte[2 * length];
        int j = 0;

        for (int i = offset; i < offset + length; i++) {
            buf[j++] = (byte) ((array[i] >>> 8) & 0xFF);
            buf[j++] = (byte) (array[i] & 0xFF);
        }
        return buf;
    }

    public static byte[] toBytes(short[] array) {
        return toBytes(array, 0, array.length);
    }
}

Related

  1. toBytes(int integer)
  2. toBytes(int intValue)
  3. toBytes(int is)
  4. toBytes(int megabytes)
  5. toBytes(int n)
  6. toBytes(int val)
  7. toBytes(int value)
  8. toBytes(int value)
  9. toBytes(int value)