Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding value of 2 bytes in Java

Tags:

java

byte

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.ByteBuffer be of any use?

Thanks

like image 933
Trevor Avatar asked Apr 13 '26 09:04

Trevor


2 Answers

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.

like image 69
Jack Avatar answered Apr 14 '26 23:04

Jack


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;
like image 33
erickson Avatar answered Apr 14 '26 22:04

erickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!