I receive a datapacket containing a byte array and I have to get some integer values from it. Here is a part of the documentation. Can someone help me please?
This comes in a 4-byte array.
Year from 1990 to 2052 (6 bit), Month from 1 to 12 (4 bit), Day from 1 to 31 (5 bit), Hour from 0 to 23 (5 bit), Minute from 0 to 59 (6 bit), Second from 0 to 59 (6 bit) Default value: 1 January 2000, 12:00:00
The format of the message is in little endian.
What you need is some bitwise operations. First, construct an int out of the bytes:
Then, chop up the int into components. Now, your question does not specify which way do the fields go, right-to-left or left-to-right. That question is related to endianness, but not identical. So let's assume that the fields go from left to right.
Good sense suggests left-to-right. This way the integer representations of time values can be compared - the significance of year bits is more than month bits etc, so when you compare integers that correspond to two moments in time, you get a chronologically correct result.
Here's a mental image for you. This is an integer variable, composed of bits:
Let's define a function that takes a arbitrary chunk from an int at a given offset (in bits), with a given length (in bits).
Could've been a one-liner, but I wanted to make it somewhat instructive. Folks in the answers below effectively inline this function, by specifying the shift factor and the mask by hand for each chunk.
Now let's decompose. Assuming n comes from the topmost snippet:
We get the values of the offset by combining the total lengths of the previous fields together. This is under the assumption that the fields go left to right; if they go the other way around, the offset values would be different.
Did that make sense?
EDIT: if the bit chunks go right to leftt, then here's how it'd go:
Assuming you have java 7, you should be able to read the year as
and the month as
I let you do the others ints in the same way.
I don't have java7 and can't test now, I hope I'm not wrong. It's also possible that the order of the bytes is the reverse one.
First, I'd convert this to an integer:
Next, I'd take it apart:
The masking in the first line and shifting in the last line are not strictly necessary, but are left in for clarity.
The final step is to add 1900 to the
yearCode
and you're done!