0

The C++ client send a byte array to the Java Server.The first two bytes indicate the length of the residual byte array.The client uses unsigned short,but there's no unsigned short in java.How can I read the first two bytes in my server?

And another problem is,in C++ the first byte indicates the lower 8 bits and the second byte indicates the upper 8 bits.For example,the two bytes is 35 02,it convert to decimal should to be 565,not 13570.

My java code like this:

    DataInputStream dis = new DataInputStream(is);
    int b1 = dis.readUnsignedByte();
    int b2 = dis.readUnsignedByte();
    int length = (b2 << 8) | b1;

It seems to work.But I can't make sure it is exact in any condition.I hope for your suggestions.thx~

Leo Xu
  • 174
  • 3
  • 11
  • so, I had a similar problem, so the answer is - it is right way. Y, it depends on endian. I tried to write some struct in a binary file with C and then to read it with Java. http://stackoverflow.com/a/10162916/1092399 . Btw, dunno exactly how can u deal with it in another way, mb there r some ready libraries for more elegant decision. I made my own class for all elementary types. – DaunnC Nov 04 '13 at 05:08
  • 1
    thx for your answer.I used my code above.It works normally in my situation. – Leo Xu Nov 04 '13 at 08:25

2 Answers2

3

Err, DataInputStream.readUnsignedShort()!

I can't make sure it is exact in any condition

You can't test 65536 values? It's not difficult.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

To convert an unsigned short to a signed int you can do

int value = dis.readShort() & 0xFFFF;

Your other problem has to do with the byte order. I suggest taking a look at the ByteBuffer which you can specify the byte order on using the order method.

WouterH
  • 1,345
  • 10
  • 16