C# – C/C++ Date Solution/Conversion


I need to come up with a way to unpack a date into a readable format. unfortunately I don't completely understand the original process/code that was used.

Per information that was forwarded to me the date was packed using custom C/Python code as follows;

  date = year << 20;
  date |= month << 16;
  date |= day << 11;
  date |= hour << 6;
  date |= minute;

For example, a recent packed date is 2107224749 which equates to Tuesday Sept. 22 2009 10:45am

I understand….or at least I am pretty sure….the << is shifting the bits but I am not sure what the "|" accomplishes.

Also, in order to unpack the code the notes read as follows;

year = (date & 0xfff00000) >> 20;
month = (date & 0x000f0000) >> 16;
day = (date & 0x0000f800) >> 11;
hour = (date & 0x000007c0) >> 6;
minute = (date & 0x0000003f);

Ultimately, what I need to do is perform the unpack and convert to readable format using either JavaScript or ASP but I need to better understand the process above in order to develop a solution.

Any help, hints, tips, pointers, ideas, etc. would be greatly appreciated.

Best Solution

The pipe (|) is bitwise or, it is used to combine the bits into a single value.

The extraction looks straight-forward, except I would recommend shifting first, and masking then. This keeps the constant used for the mask as small as possible, which is easier to manage (and can possibly be a tad more efficient, although for this case that hardly matters).

Looking at the masks used written in binary reveals how many bits are used for each field:

  • 0xfff00000 has 12 bits set, so 12 bits are used for the year
  • 0x000f0000 has 4 bits set, for the month
  • 0x0000f800 has 5 bits set, for the day
  • 0x000007c0 has 5 bits set, for the hour
  • 0x0000003f has 6 bits set, for the minute