0

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!

Nico812
  • 47
  • 5

2 Answers2

1

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);
}
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Perfect !! Thanks, it works ! Sorry, could you explain me what did you do? Because then I have to save a datetime in byte array and I want to know how to make the inverse. – Nico812 May 18 '15 at 23:31
  • I combined the two values into a single 16-bit value, then just extracted the portions I needed. – David Schwartz May 18 '15 at 23:37
  • Thanks David , you helped me a lot ! – Nico812 May 18 '15 at 23:45
  • David, sorry the last question.. I understood that you combined the two values in 16 bits and then shift the bits , in case of day in 11 bits, to get the 5 restant. But I dont understand the part of the mask that you put & 31 ..&127...&15. If it isn't bothering much could you explain me that? Thanks again !! – Nico812 May 19 '15 at 00:02
  • That extracts just the rightmost (lower) bits and masks out the others. – David Schwartz May 20 '15 at 00:10
0

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.

rmalchow
  • 2,689
  • 18
  • 31