简体   繁体   中英

Raw data parsing

I have a byte array with length is 18 with the following structure:

unsigned int a;
unsigned int b;
unsigned short c;
unsigned long d;

I know that I don't have unsigned * data type in Java. After searching form web, I find that I should use a bigger data type to store the value. For example, I should use int to store an unsigned short variable.

I have two questions. The first one is how to parsing the byte array to get the value from the array to the variable I am using. The second one is how to handle unsigned long variable? I know that may be BigInteger can help me but I am not sure how to work it out.

There are at least two practical ways to decode the data. Either you could do the byte-fiddling manually like this (assuming little-endian):

a = (array[0] & 0xff) | ((array[1] & 0xff) << 8) | ((array[2] & 0xff) << 16) | ((array[3] & 0xff) << 24);
// Analogously for the others
// The "& 0xff"s are for stripping sign-extended bits.

Alternatively, you can use a java.nio.ByteBuffer :

ByteBuffer buf = ByteBuffer.wrap(array);
buf.order(ByteOrder.LITTLE_ENDIAN);
a = buf.getInt();
// Analogously for the others

There are, of course, an infinitude of ways to go about it; these were just examples. Initializing a DataInputStream from a ByteArrayInputStream could be another example.

As for handling unsigned long s, Java obviously can't do it generally, but depending on what kind of operations you intend to carry out on them, you may not have to care. General bit-fiddling like ANDs, ORs and bit-shifting generally, and also simple arithmetic like addition and subtraction, don't care about signedness, after all (though do check out the differences between >> and >>> ).

If you really want to do general unsigned long arithmetic, then indeed BigInteger s are probably your only (practical) way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM