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

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert An Int To A Byte Array

04.09.2005
| 320260 views |
  • submit to reddit
        
    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

simply make logical AND with your byte and 0xFF: it will be: System.out.println(Integer.toHexString(0xff & xs[i]));

Snippets Manager replied on Thu, 2009/04/23 - 10:52am

hi toxi, I already tried your solution but I keep having the same problem with the signed int... I use this: public static final byte[] intToByteArray(int value) { return new byte[]{ (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) }; } and from my main I call the function as: byte[] xs = pruebaPaquetes_.intToByteArray(0xABC12345); for(int i=0; i

Ann Nan replied on Tue, 2008/11/11 - 6:22am

What about big-endian?

Snippets Manager replied on Thu, 2007/11/15 - 6:19pm

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.

Snippets Manager replied on Mon, 2012/05/07 - 2:11pm

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) }; }