I am reading a Let us C book, in that to store date in two bytes formula is there
int year = 1990, month = 03, day=22
date = 512*(year-1980)+32*month+day
I do not understand the above formula, like why 1980 is being subtracted from given year and multiplying with 512 then multiplying 32 with month and adding day.
Could someone please explain me above formula. Thanks in advance.
The above formule just store the day (1-31 or 0-30) on 5 digits, the month (0-11 or 1-12) on 4 digits and the year on 7 digits to put it in only 2 bytes.
The epoch here is year 1980, that means that all will be fine for years between 1980 and 2127. My advice would be to avoid negative values and choose an appropriate start year. For example date = 512*(year-1950)+32*month+day
would be fine for years between 1950 and 2077.
I advise you to avoid negative values because right shift of signed value is defined by standard as implementation dependant so you cannot know if the new bits will be filled with 1 or with 0. So even if you want to process negative values, always use unsigned short
for you 2 byte values or uint16_t
to have deterministic shifts.