Finding a value of 2 bytes in Java

I am trying to find the value of the first 2 bytes in a UDP packet that matches the length of the remaining payload. What is the best way to find this value in Java, given that I know the first 2 bytes? Will java.nio.ByteBufferuse?

thank

+3
source share
4 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 the first two bytes of yours DatagramPacket:

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

Remember that I used length as int, because also the data type short(like every one) is signed in Java, so you need more space.

+5
source

ByteBuffer , 16- , Java:

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;
}

ByteBuffer, . , :

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

You really can use java.nio.ByteBuffer. Here is an example run:

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.
+2
source

Using ByteBuffer will only matter if you are reading UDP packets (using nio). You can create a useful method:

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

Source: https://habr.com/ru/post/1748560/


All Articles