Leo Xu
Leo Xu

Reputation: 174

Java How to read unsigned short using inputstream?

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~

Upvotes: 0

Views: 5135

Answers (2)

user207421
user207421

Reputation: 310909

Err, DataInputStream.readUnsignedShort()!

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

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

Upvotes: 3

WouterH
WouterH

Reputation: 1356

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.

Upvotes: 1

Related Questions