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
Ahsan Gill replied on Fri, 2013/05/10 - 5:37am
event security newry event security lisburn event security londonderry event security belfast event security armagh event security county-armagh event security swansea event security st asaph event security newport event security cardiff event security bangor
Snippets Manager replied on Mon, 2009/11/30 - 4:55am
Snippets Manager replied on Thu, 2009/04/23 - 9:52am
Ann Nan replied on Tue, 2008/11/11 - 5:22am
Snippets Manager replied on Thu, 2007/11/15 - 5: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 - 1:11pm