Question

I need to recover from a DatagramPacket 2 primitive data type, and an array of bytes;

I need to get an unsigned long long, and an int as primitive Data Type... When I try by manually copying with System.arraycopy each variable, it seems to mess with the endianness I don't get the same values as it has been sent... Plus I'm not sure which Data type is equivalent from unsigned long long in Java...

The first variable is a timestamp, the second is the size of the next array of byte I should get...

With C language I managed to do that simply by using :

unsigned long long timestamp = 0;
memcpy(&timestamp, packetData, sizeof(unsigned long long));
packetData += sizeof(unsigned long long);
int sizePacket;
memcpy(&sizePacket, packetData, sizeof(int));
packetData += sizeof(int);
char *encodedData = (char*)malloc(sizePacket);
if (encodedData != nil)
   memcpy(encodedData, packetData, sizePacket);
Was it helpful?

Solution

I use long as a 64-bit value. If it is timestamp you might not need to worry about overflows, but if you are there are way to correct for this. A 32-bit int value is just int in Java.

System.arraycopy just copies bytes, it has no idea about endianness and doesn't change it.

Most likely you want to use ByteBuffer with native byte order. and you will get what you want.

DatagramSocket ds = ...
ByteBuffer bb = ByteBuffer.wrap(ds.getData()).order(ByteOrder.nativeOrder());
long timestamp = bb.getLong();
int number = bb.getInt();
// use the bb to read the encoded data.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top