Java Byte Array Create toByteArray(final int i, final byte[] output, final int offset)

Here you can find the source of toByteArray(final int i, final byte[] output, final int offset)

Description

Converts an integer to a byte array.

License

Open Source License

Parameter

Parameter Description
i the integer to be converted
output the output buffer
offset the offset of the first byte to be written

Declaration

public static void toByteArray(final int i, final byte[] output, final int offset) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w w  w.ja v a 2 s .  c o m*/
     * Number of bits on a byte.
     */
    public static final int BIT_SIZE_OF_BYTE = 8;
    /**
     * The mask of a byte from an integer. Used to simulate a fast coercion of integer to
     * byte.
     */
    public static final int INT_LOW_BYTE_MASK = 0x000000FF;

    /**
     * Converts an integer to a byte array.
     * <p>
     * Assumes that output.length > offset + 4
     * 
     * @param i the integer to be converted
     * @param output the output buffer
     * @param offset the offset of the first byte to be written
     */
    public static void toByteArray(final int i, final byte[] output, final int offset) {
        final int firstByteOffset = 0;
        final int secondByteOffset = 1;
        final int thirdByteOffset = 2;
        final int fourthByteOffset = 3;
        output[offset + firstByteOffset] = (byte) (i & INT_LOW_BYTE_MASK);
        output[offset + secondByteOffset] = (byte) ((i >> secondByteOffset * BIT_SIZE_OF_BYTE) & INT_LOW_BYTE_MASK);
        output[offset + thirdByteOffset] = (byte) ((i >> thirdByteOffset * BIT_SIZE_OF_BYTE) & INT_LOW_BYTE_MASK);
        output[offset + fourthByteOffset] = (byte) ((i >> fourthByteOffset * BIT_SIZE_OF_BYTE) & INT_LOW_BYTE_MASK);
    }
}

Related

  1. toByteArray(final byte[][] array)
  2. toByteArray(final char[] array)
  3. toByteArray(final char[] array)
  4. toByteArray(final int i)
  5. toByteArray(final int i)
  6. toByteArray(final int value)
  7. toByteArray(final String bitString)
  8. toByteArray(final String hexString)
  9. toByteArray(int data)