-2

I have an int array that i obtained by using RobotPeer.getRGBPixels(). I convert it to an byte array to send it over socket by using:

 public static byte[] toByteArray(int[] ints){
    byte[] bytes = new byte[ints.length * 4];
            for (int i = 0; i < ints.length; i++) {
        bytes[i * 4] = (byte) (ints[i] & 0xFF);
        bytes[i * 4 + 1] = (byte) ((ints[i] & 0xFF00) >> 8);
        bytes[i * 4 + 2] = (byte) ((ints[i] & 0xFF0000) >> 16);
        bytes[i * 4 + 3] = (byte) ((ints[i] & 0xFF000000) >> 24);
    }
    return bytes;
}

Problem is: I use this method:

public static int[] toIntArray(byte buf[]) {
    int intArr[] = new int[buf.length / 4];
    int offset = 0;
    for (int i = 0; i < intArr.length; i++) {
        intArr[i] = (buf[3 + offset] & 0xFF) | ((buf[2 + offset] & 0xFF) << 8)
                | ((buf[1 + offset] & 0xFF) << 16) | ((buf[0 + offset] & 0xFF) << 24);
        offset += 4;
    }
    return intArr;
}

to get back int array. Then i create BufferedImage from it and i get: https://www.dropbox.com/s/p754u3tnivigu70/test.jpeg

Please help me to solve that problem.

mr.icetea
  • 2,607
  • 3
  • 24
  • 42
  • You have the wrong byte order. Possible duplicate of [Byte Array and Int conversion in Java](http://stackoverflow.com/questions/5399798/byte-array-and-int-conversion-in-java) – Brian Roach Mar 26 '14 at 05:53
  • Use `ByteBuffer`s; they will manage bit handling for you and you can specify the endianness to use – fge Mar 26 '14 at 06:24
  • @BrianRoach thank you, i sovled it. Sorry for create duplicate question, next time i will try to find out. – mr.icetea Mar 26 '14 at 07:59

1 Answers1

3

Don't bother with bit shifting etc; Java has ByteBuffer which can handle that for you, and endianness to boot:

public static int[] toIntArray(byte buf[]) 
{
    final ByteBuffer buffer = ByteBuffer.wrap(buf)
        .order(ByteOrder.LITTLE_ENDIAN);
    final int[] ret = new int[buf.length / 4];
    buffer.asIntBuffer().put(ret);
    return ret;
}

Similarly, the reverse:

public static byte[] toByteArray(int[] ints)
{
    final ByteBuffer buf = ByteBuffer.allocate(ints.length * 4)
        .order(ByteOrder.LITTLE_ENDIAN);
    buf.asIntBuffer().put(ints);
    return buf.array();
}

Don't forget to specify endianness in your case since ByteBuffers are big endian by default.

fge
  • 119,121
  • 33
  • 254
  • 329