231

I got an integer: 1695609641

when I use method:

String hex = Integer.toHexString(1695609641);
system.out.println(hex); 

gives:

6510f329

but I want a byte array:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};

How can I make this?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
stefan
  • 2,313
  • 2
  • 14
  • 4
  • 5
    possible duplicate of [Convert integer into byte array (Java)](http://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java) – finnw Jul 27 '10 at 14:14
  • Possible duplicate of [Convert integer into byte array (Java)](https://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java) – Tacodiva Feb 11 '19 at 05:44

14 Answers14

344

using Java NIO's ByteBuffer is very simple:

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

output:

0x65 0x10 0xf3 0x29 
dfa
  • 114,442
  • 31
  • 189
  • 228
186

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106
  • 2
    -1 Not a good idea to hand-code things like this; that's what properly-tested and reviewed JDK libraries are for. – Kevin Bourrillion Feb 02 '10 at 15:33
  • 53
    I see your point, but for this particular task 'my' code is more declarative and clear than some 'magic' ByteBuffer, which one has to check to see what it does. – Grzegorz Oledzki Feb 02 '10 at 20:50
  • 27
    @Kevin - that's very harsh - there are plenty of cases where this kind of code is appropriate, e.g. in image processing. The JDK libraries are great in general, but they don't cover and/or aren't optimised for all use cases. – mikera Apr 26 '11 at 14:50
  • 19
    agreed; the overhead and complexity of ByteBuffer may not be appropriate compared to some simple and well known byte operations. – swdunlop May 03 '11 at 02:27
  • 8
    Another point I'd add is that you've used the unsigned right shift operator `>>>` rather than the right shift operator `>>` (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) so behavior may not be as desired/as expected with signed vs unsigned numbers – RobV May 07 '12 at 11:37
  • 4
    This approach seems to be a tad faster than the ByteBuffer or BigInteger methods mentioned. Something else to take into account if you will be doing a lot of conversions. – seeker Jan 24 '13 at 08:55
  • 3
    +1, this solution also works for J2ME, where ByteBuffer (accepted answer) may not be available. – Nate Mar 10 '13 at 03:39
  • 1
    Code to go back to integer again is here: http://stackoverflow.com/a/5399829/418057 – Craigo Sep 06 '14 at 03:48
  • 6
    Note: this is BigEndian. If you need LittleEndian you have to reverse the order. – luckydonald May 12 '16 at 08:21
  • 1
    some post on dzone.com: Does not exist anymore – Moritz Schmidt Nov 05 '17 at 00:11
  • 5
    @RobV Because of the cast to `(byte)`, the flavor of the shift won't matter in this case. If the number of bits-shifted were not a multiple of 8 in each case, there *would* be a difference. – Christopher Schultz Dec 10 '18 at 19:32
55

BigInteger.valueOf(1695609641).toByteArray()

Marijn
  • 10,367
  • 5
  • 59
  • 80
vmpn
  • 673
  • 5
  • 5
  • 4
    what guarantee do you have that that will produce a 4 byte array? – MeBigFatGuy Oct 05 '13 at 04:40
  • 2
    Exactly what MeBigFatGuy wrote. Javadoc of `BigInteger.toByteArray()` states: "The array will contain the minimum number of bytes required to represent this BigInteger..." – icza Dec 05 '13 at 08:02
  • 2
    Where in the question does it ask for the byte array to be of fixed length 4? Depending on algorithm this is meant to be part of you can utilize the length of the array – vmpn Apr 20 '14 at 15:51
  • this is much more dynamic and should be the right answer. You can simply do an Array append to create the desired size if you like. Specially when you have to consider Java signed int values. – Droid Chris Mar 11 '15 at 18:23
  • 3
    This seems to create one byte for 0x7f and two bytes for 0x80 ( the two bytes being: 0x0 0x80 ). – Scot Aug 11 '15 at 17:23
  • yeah it must be converting to the two's-compliment interpretation of the number – ZMitton Nov 10 '17 at 20:25
31
byte[] IntToByteArray( int data ) {    
    byte[] result = new byte[4];
    result[0] = (byte) ((data & 0xFF000000) >> 24);
    result[1] = (byte) ((data & 0x00FF0000) >> 16);
    result[2] = (byte) ((data & 0x0000FF00) >> 8);
    result[3] = (byte) ((data & 0x000000FF) >> 0);
    return result;        
}
db80
  • 4,157
  • 1
  • 38
  • 38
Yury Finchenko
  • 1,035
  • 13
  • 19
29

Using Guava:

byte[] bytearray = Ints.toByteArray(1695609641);
Aleksandr Dubinsky
  • 22,436
  • 15
  • 82
  • 99
7
public static byte[] intToBytes(int x) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);
    out.writeInt(x);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}
lyon819
  • 89
  • 1
  • 2
7
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
  • 2
    That extracts the least significant 8 bytes. It also avoids dragging the input number's sign into the converted octet. – Carl Smotricz May 30 '14 at 13:42
  • http://stackoverflow.com/questions/35305634/how-to-write-this-c-sharp-four-bytes-of-length-info-in-java - can you please solve this C# into Java? –  Feb 10 '16 at 07:12
4

Because generally you would want to convert this array back to an int at a later point, here are the methods to convert an array of ints into an array of bytes and vice-versa:

public static byte[] convertToByteArray(final int[] pIntArray)
{
    final byte[] array = new byte[pIntArray.length * 4];
    for (int j = 0; j < pIntArray.length; j++)
    {
        final int c = pIntArray[j];
        array[j * 4] = (byte)((c & 0xFF000000) >> 24);
        array[j * 4 + 1] = (byte)((c & 0xFF0000) >> 16);
        array[j * 4 + 2] = (byte)((c & 0xFF00) >> 8);
        array[j * 4 + 3] = (byte)(c & 0xFF);
    }
    return array;
}

public static int[] convertToIntArray(final byte[] pByteArray)
{
    final int[] array = new int[pByteArray.length / 4];
    for (int i = 0; i < array.length; i++)
        array[i] = (((int)(pByteArray[i * 4]) << 24) & 0xFF000000) |
                (((int)(pByteArray[i * 4 + 1]) << 16) & 0xFF0000) |
                (((int)(pByteArray[i * 4 + 2]) << 8) & 0xFF00) |
                ((int)(pByteArray[i * 4 + 3]) & 0xFF);
    return array;
}

Note that because of sign propagation and such, the "& 0xFF..." are needed when converting back to the int.

jytou
  • 510
  • 4
  • 7
4

If you're using apache-commons

public static byte[] toByteArray(int value) {
    byte result[] = new byte[4];
    return Conversion.intToByteArray(value, 0, result, 0, 4);
}
Neeraj
  • 2,376
  • 2
  • 24
  • 41
  • This would be good but "Conversion" is in Apache Commons Lang 3 which is for Java 8+. Unfortunately I still require Java 7 compatibility :( – user96279 Dec 14 '22 at 17:38
2
integer & 0xFF

for the first byte

(integer >> 8) & 0xFF

for the second and loop etc., writing into a preallocated byte array. A bit messy, unfortunately.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

The chunks below work at least for sending an int over UDP.

int to byte array:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

byte array to int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}
HaoQi Li
  • 11,970
  • 14
  • 58
  • 77
  • 6
    use of ObjectOutputStream is incorrect. Use DataOutputStream, use of OOS makes it so the byte array is not 4 bytes. – MeBigFatGuy Oct 05 '13 at 04:46
  • MeBigFatGuy is correct. The bytes array includes other bytes as well, surely more than 4 expected. – AlexeiOst Aug 12 '22 at 21:28
1

My try :

public static byte[] toBytes(final int intVal, final int... intArray) {
    if (intArray == null || (intArray.length == 0)) {
        return ByteBuffer.allocate(4).putInt(intVal).array();
    } else {
        final ByteBuffer bb = ByteBuffer.allocate(4 + (intArray.length * 4)).putInt(intVal);
        for (final int val : intArray) {
            bb.putInt(val);
        }
        return bb.array();
    }
}

With it you can do this :

byte[] fourBytes = toBytes(0x01020304);
byte[] eightBytes = toBytes(0x01020304, 0x05060708);

Full class is here : https://gist.github.com/superbob/6548493, it supports initialization from shorts or long

byte[] eightBytesAgain = toBytes(0x0102030405060708L);
superbob
  • 1,628
  • 13
  • 24
1

The class org.apache.hadoop.hbase.util.Bytes has a bunch of handy byte[] conversion methods, but you might not want to add the whole HBase jar to your project just for this purpose. It's surprising that not only are such method missing AFAIK from the JDK, but also from obvious libs like commons io.

mlohbihler
  • 717
  • 1
  • 7
  • 15
0

Here are two function to do the mirrored thing:

    byte[] intToBytes(int i) {
        return new byte[]{
                (byte) (i >>> 24),
                (byte) (i >>> 16),
                (byte) (i >>> 8),
                (byte) i
        };
    }
    int bytesToInt(byte[] b) {
        //Cuz int encode by complement-on-two
        //For a negative, signed left shift operation will Fill the upper part of the binary with 1.
        //That‘s a question for us to combine the meaningful part.

        //Here, we execute a AND 0xFF operation, to implicitly convert a byte to int, and fill  the upper part of the binary with 0
        //So ,we got a positive number now.
        //The next step just execute OR operation to combine the four part as an integer.
        return (b[0]) << 24 |
                (b[1] & 0xFF) << 16 |
                (b[2] & 0xFF) << 8 |
                (b[3] & 0xFF);
    }

light
  • 113
  • 4