开发者

Finding value of 2 bytes in Java

I am trying to find the value of the first 2 bytes in a UDP packet which corresponds to the length of the remaining payload. What is the best method to find this value in Java given that I know the first 2 bytes? Would java.nio.ByteBuff开发者_高级运维er be of any use?

Thanks


I usually use something like this:

static public int buildShort(byte high, byte low)
{
  return ((0xFF & (int) high) * 256) + ((0xFF & (int) low));
}

Then you take first two bytes of your DatagramPacket:

int length = buildShort(packet.getData()[0], packet.getData()[1]);

Mind that I used length as an int because also short data type (as everyone) is signed in Java, so you need a larger space.


Using a ByteBuffer is convenient, just don't get tripped up by Java signed 16-bit values:

byte[] data = new byte[MAX_LEN];
ByteBuffer buf = ByteBuffer.wrap(data);
DatagramPacket pkt = new DatagramPacket(data, data.length);
⋮    
while (connected) {
  socket.receive(pkt);
  int len = buf.getShort() & 0xFFFF;
  ⋮
}

If you don't want to use ByteBuffer, the conversion is still fairly easy. The equivalent multiplication and addition can be used, but I see bit operators used more frequently:

int len = (data[0] & 0xFF) << 8 | data[1] & 0xFF;


You can indeed make use of java.nio.ByteBuffer. Here's a kickoff example:

ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(byte1);
buffer.put(byte2);
int length = buffer.getShort(0) & 0xFFFF; // Get rid of sign.


Using ByteBuffer would only be of value if you are reading the UDP packets (using nio). You can create a utility method:

static final int getLength(DatagramPacket packet) {
 byte data[] = DatagramPacket.getData();
 return (int)((0xFF & (int)data[0]) << 8) | (0xFF & (int)data[1]));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜