Convert an int to a byte array,Java Programming - integer to byte

Hi,
Could someone tell me how to convert a int, say 500000, to a byte[]?

Integer class has a byteValue() method, but it only returns a single byte, what if the integer number is large, 32-bit.

Thank you very much.



int number = 50000;

byte[] byteArray = new byte[4];

byteArray[0] = (byte)((number >> 24) & 0xFF);

byteArray[1] = (byte)((number >> 16) & 0xFF);

byteArray[2] = (byte)((number >> 8) & 0xFF);

byteArray[3] = (byte)(number & 0xFF);















All those solutions are converting a 32-bit integer to a byte array, in "big-endian" way. If your integer is

int i = 0x12345678;

the resulting byte array will be:

b[0] = 0x12; b[1] = 0x34; b[2] = 0x56; b[3] = 0x78;

Usually it is what you want. But if you want to convert it to "little-endian" way (as found in Intel and Digital Alpha machines) simply invert the bytes.

b[0] = 0x78; b[1] = 0x56; b[2] = 0x34; b[3] = 0x12;







 

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.

你可能感兴趣的:(programming)