0

I have a server-client communication channel based on sockets. I packed 3 integer value to byte[] and write it to socket OutputStream, but i how to convert it back?

Pease of code :

    ByteBuffer b = ByteBuffer.allocate(12);
    b.putInt(BTActions.READY_FOR_GAME);
    b.putInt(i);
    b.putInt(l);

    try
    {
        mAcceptThread.getWriteSocket().write(b.array());
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
S.Shustikov
  • 93
  • 1
  • 1
  • 4

1 Answers1

0

If you use a ByteBuffer, this buffer has a byte order; and this order is big endian by default.

You allocate a 12-byte buffer and write 3 ints to it; that is 12 bytes, so far so good.

Given that you do not define an order to the ByteBuffer, the default is big endian. And big endian is what the JVM uses for all primitive types by default.

Therefore, after having written 3 ints to your buffer, you can read them back as:

final int i1, i2, i3;
buffer.rewind();
i1 = buffer.getInt();
i2 = buffer.getInt();
i3 = buffer.getInt();
fge
  • 119,121
  • 33
  • 254
  • 329
  • So if i put 3 int values like a 5,8,7 i must rewind buffer to get this value or integers in the reverse order? – S.Shustikov Jul 05 '13 at 22:19
  • When you `.put*()` to a `ByteBuffer`, you change that buffer's offset (if you have a look at the javadoc, this is relative put operations). There are also absolute put operations, but there is no such operation for an `int` on a `ByteBuffer`. At worst, it you want to read anew, you can always do `final ByteBuffer newbuf = ByteBuffer.wrap(oldbuf.array());` and read back – fge Jul 05 '13 at 22:22