convert int to bytes. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

convert int to bytes.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int value = 2;
        System.out.println(java.util.Arrays.toString(toBytes(value)));
    }/*from  www .  j  a v a 2  s .  c o m*/

    /** nbr of bytes. */
    private static final int BYTE_LENGTH = 4;
    /** nbr of shift positions. */
    private static final int BYTE_SHIFT = 8;
    /** const for and op. */
    private static final long AND_OP = 0xFFL;

    /**
     * convert int to bytes.
     * 
     * @param value
     *            int to convert to bytes
     * @return byte[] int as bytes
     */
    public static byte[] toBytes(int value) {
        int workValue = value;
        byte[] result = new byte[BYTE_LENGTH];
        for (int i = (BYTE_LENGTH - 1); i >= 0; i--) {
            result[i] = (byte) ((AND_OP & workValue) + Byte.MIN_VALUE);
            workValue >>>= BYTE_SHIFT;
        }
        return result;
    }

    /**
     * convert short to bytes.
     * 
     * @param value
     *            short to convert
     * @return byte[] short as bytes
     */
    public static byte[] toBytes(short value) {
        short workValue = value;
        byte[] result = new byte[2];
        for (int i = 1; i >= 0; i--) {
            result[i] = (byte) ((AND_OP & workValue) + Byte.MIN_VALUE);
            workValue >>>= BYTE_SHIFT;
        }
        return result;
    }
}

Related Tutorials