Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Convert an int to a byte array (See related posts)

    public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }

Comments on this post

toxi posts on Sep 12, 2006 at 19:14
a much faster (60%) version would be that:

public static final byte[] intToByteArray(int value) {
return new byte[]{
(byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
}
MichaelTague posts on Nov 15, 2007 at 18:12
The masks aren't necessary. The byte casts do the job:

public static final byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
}


The inverse of this, byte array to int, would be:

public static final int byteArrayToInt(byte [] b) {
        return (b[0] << 24)
                + ((b[1] & 0xFF) << 16)
                + ((b[2] & 0xFF) << 8)
                + (b[3] & 0xFF);
}

The masks are needed here because when the byte is widened to an int sign extension may add lots of bits that we get ride of with the mask.

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts