0

Currently I am working on socket programming where I have to send array of bytes to the firmware.The below code is for converting int into byte array.

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

}

Can anyone make me understand how this right shift works,with small example.

and this is the oposite converting byte into int.

  public static int byteArrayToInt(byte[] b) {
    return b[0] & 0xFF
            | (b[1] & 0xFF) << 8
            | (b[2] & 0xFF) << 16
            | (b[3] & 0xFF) << 24;
}

How this left shift and right shift works.

Ravi Godara
  • 497
  • 6
  • 20

3 Answers3

1

Actually, you can simply convert int value to 4 byte array using the below statement.

return ByteBuffer.allocate(4).putInt(intVal).array();

But before implementing this, first have a look at the documentation of ByteBuffer, especially on the order method.

In order to understand the left shift & right shift, go to this StackOverflow answer: Java: right shift on negative number

Shishir

Community
  • 1
  • 1
Shishir Kumar
  • 7,981
  • 3
  • 29
  • 45
0

Use a ByteBuffer:

public static byte[] intToBytes(final int i)
{
    return ByteBuffer.allocate(4).putInt(i).array();
}

public static int bytesToInt(final byte[] b)
{
    return ByteBuffer.wrap(b).getInt();
}

Note that the default ordering is big endian. This is the JVM's, and also network, byte order.

fge
  • 119,121
  • 33
  • 254
  • 329
0

Things to know to understand that code:

  • int to byte conversion cuts off the 3 most significant bytes of the int.
  • Shifts
  • Bitmasks
  • When you hard-code the value 0xFF it's actually an int (0x000000FF). You & the bytes with it to get rid of the leading 1's you get in signed byte-to-int conversion when the byte is negative (has a 1 in the most significant bit).

So suppose your int was 0x1A2B3C4D:

public static byte[] intToFourByteArray(int value) {
    return new byte[]{
        (byte) (value),        // Cuts off top, leaves 0x4D
        (byte) (value >> 8),   // Shift gives 0x001A2B3C, cut-off leaves 0x3C
        (byte) (value >> 16),  // Shift gives 0x00001A2B, cut-off leaves 0x2B
        (byte) (value >> 24)}; // Shift gives 0x0000001A, cut-off leaves 0x1A

}

And suppose we fed the byte array 0x4D, 0x3C, 0x2B, 0x1A back:

public static int byteArrayToInt(byte[] b) {
    return b[0] & 0xFF             // That gives 0x0000004D
            | (b[1] & 0xFF) << 8   // Gives 0x0000003C then shifts to 0x00003C00
            | (b[2] & 0xFF) << 16  // Same idea, giving 0x002B0000
            | (b[3] & 0xFF) << 24; // ...and 0x1A000000
}                                  // Finally, the or-ing of them together gives 0x1A2B3C4D
trutheality
  • 23,114
  • 6
  • 54
  • 68