Reputation: 47
I have to parse a field, that have 2 bytes, and saves a datetime information. To get the datatime, this field has this structure:
5 bits for day , 4 bits for month , and 7 bits for year (total 16 bits)
To get the day I am using :
byte day = (byte)(array[0] >> 3); (that's ok )
I could get the year too, but I can't get the month value, could you help me with this?
The array value is : {243,29} and I have to get this datetime: 30/6/2019
Thanks!
Upvotes: 0
Views: 93
Reputation: 2769
given your comment, i guess the problem you are having is the bitwise OR and AND operators, which, in java would be "|" and "&" - with other languages, it might be different, but it does exist.
a bitwise "|" helps you combine the bits from two bytes:
0000 0001 | 0000 0010 ----> 0000 0011
while bitwise "&" helps you mask out some bits:
0101 0110 & 1111 0000 ----> 0101 0000
with the bitwise shift operator (that you are already using), you can move bits (">>" or "<<"), extract certain bits while ignoring others ("&") and combine bits ("|").
this means, you can extract three month bits from the first byte, move them over one bit, then extract the remaining bit from the second byte, and finally combine those two.
Upvotes: 0
Reputation: 182827
Translate into the language of your choice.
#include <stdio.h>
int array[2] = { 243,29 };
int main(void)
{
int fullval = array[0] << 8 | array[1];
int day = (fullval >> 11) & 31;
int year = 1990 + (fullval & 127);
int month = (fullval >> 7) & 15;
printf ("%d/%d/%d\n", day, month, year);
}
Upvotes: 1