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.08.2005
| 352637 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

Engr Ubaid Masood replied on Thu, 2014/02/13 - 12:17am

Hello World,

Really appreciate the blogs and sensible comments , keep sharing

regards,


bodyguard services,London
follow us : http://www.ibodyguardlondon.com

Hire security in london

Ievent Security
follow us : http://www.ieventsecurity.co.uk

Royal Armor Group

construction site security in london

follow us on: http://www.royalarmorgroup.com

Oliverz

hire domestic workers in london hire domestic workers in london

http://www.oliverz.co.uk

Snippets Manager replied on Mon, 2009/11/30 - 4: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 - 9: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 - 5:22am

What about big-endian?

Snippets Manager replied on Thu, 2007/11/15 - 5: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 - 1: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) }; }