I have a short counter which increments and is used as an identifier. I need to send the identifier as binary data on a network socket.
So if I have a short value I can do this to ‘pack’ in two bytes:
short id = 1;
byte val = (byte)(id & 0xFF);
byte val2 = (byte)((id >>> 8) & 0xFF);
System.out.printf("id=%d, val = id & 0xFF = %d, val2 = (id >>> 8) & 0xFF = %d\n",
id, val, val2);
Now when id = 1 this works fine.
But when id = 255 I get:
short id = 255;
byte val = (byte)(id & 0xFF); //val = -1
byte val2 = (byte)((id >>> 8) & 0xFF); //val2 = 0
Now I know that 255 in binary is 11111111 and this means -1 for a java byte value. Am I correct in thinking that how java interprets it is immaterial and if I send as byte binary 11111111 then at the other end it can interpret this however it wants?
Yes, your thinkings are right.
Just for your information: there is a very nice class that does this for you. It is called
DataInputStreamandDataOutputStream.