Search code examples
javaarraysasciidatagram

Need to convert byte array/ binary message from UDP DatagramPacket to several fields in java


I have a byte array that consists of a 10 byte message. I know the first 2 bytes contains an id that would like to extract out to a string. An example of this id is: 2001. The remaining bytes consist of other fields which I am aware.

I am receiving the binary data from a UDP message and after attempting to convert the binary/ byte array with the methods below, my print still logs a binary message.

The code I am using is as follows to convert the binary UDP message:

 DatagramPacket rcvMsg = receivepacket.getData();
 String id = new String(rcvMsg, 0, 2, "US-ASCII");
 System.out.println("id ----- : "+id);

How can I get this to print 2001 from the binary datagram message?


Solution

  • In what format do you want recover the first 2 bytes? Do they represent an integer, or are they an encoded string?

    Because, otherwise you could wrap your array into ByteArrayInputStream, and this latter into a DataInputStream, and then read your message as you consider appropriate, by using the DataInputStream methods.

    DataInput input = new DataInputStream(new ByteArrayInputStream(myArray));
    String id = String.valueOf(input.readShort())
    

    You could even continue to use this object to read the rest of the fields encoded in the array if they correspond to supported Java data types (i.e. byte, short, int, String, etc).

    Now, if your first two bytes represent just ASCII characters (or any other encoding), then you are good to go with one of the String constructors:

    String id = new String(myBytes, 0, 2, "US-ASCII");