integer to Byte Array - Java java.lang

Java examples for java.lang:byte Array to int

Description

integer to Byte Array

Demo Code


//package com.java2s;

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

    public static byte[] toByteArray(int in) {
        byte[] out = new byte[4];

        out[0] = (byte) in;
        out[1] = (byte) (in >> 8);
        out[2] = (byte) (in >> 16);
        out[3] = (byte) (in >> 24);

        return out;
    }

    public static byte[] toByteArray(int in, int outSize) {
        byte[] out = new byte[outSize];
        byte[] intArray = toByteArray(in);
        for (int i = 0; i < intArray.length && i < outSize; i++) {
            out[i] = intArray[i];
        }
        return out;
    }

    public static String toString(byte[] theByteArray) {
        StringBuffer out = new StringBuffer();
        for (int i = 0; i < theByteArray.length; i++) {
            String s = Integer.toHexString(theByteArray[i] & 0xff);
            if (s.length() < 2) {
                out.append('0');
            }
            out.append(s).append(' ');
        }
        return out.toString();
    }
}

Related Tutorials