DZone 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
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
Snippets Manager replied on Mon, 2009/11/30 - 5:55am
Snippets Manager replied on Thu, 2009/04/23 - 10:52am
Ann Nan replied on Tue, 2008/11/11 - 6:22am
Snippets Manager replied on Thu, 2007/11/15 - 6:19pm
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.Snippets Manager replied on Mon, 2012/05/07 - 2:11pm