I have hypothetical data coming from a UDP connection that is in binary form.
Its composed of 5 fields, with a size of 25 bits
their offsets as follows
1. 0-4 ID
2. 5-10 payload
3. 11-12 status
4. 13-23 location
5. 23-25 checksum
How do I read in this data?
DatagramSocket serverSocket = new DatagramSocket(18000);
byte[] receiveData = new byte[1024];
while (true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
//not sure how I should be reading the raw binary data back in
}
How would I store off this data?
DatagramPacket’s getData returns the payload as a byte[]. You can use Arrays.copyOfRange to get the individual fields (I’m assuming you meant bytes in your question, not bits):
After this step you’ll have your fields as individual byte arrays, probably some postprocessing/reassembly into other types will be necessary. During this step probably the most annoying thing is that all Java’s types are signed whereas in many communication protocols unsigned entities are used, so be careful during this step.
Not mentioned in your question but you might need it later on: assembly of messages for transmission. I like to use GNU Trove’s TByteArrayList for that task as you don’t need to worry about reserving a byte[] with the correct length before you start, just copy in bytes or message segements and once you’re done call toArray and voilà, your byte[] is ready for transmission.