Clear LSB of year and insert byte


My program takes in a date time packet from a hardware device, which is of type byte. An example packet is:

byte[] packet = new byte[] {0x0C, 0x01, 0x15};

//packet[0] is the last two numbers of the year

As stated in the comments, packet[0] represents the last two numbers of the year. So, for example, this would translate to 2012 in decimal.

Now my question is, how do I return 2012 to the user? For the first two numbers of the year, "20", I know I can call:

int systemYear = DateTime.Now.Year;

Which returns: 0x000007dc, or 20'12' in decimal. I need no somehow remove the last two numbers from the year, in this case "12" and insert the packet[0] byte in that location instead.

I don't always want to assume we are in the year "20XX". If this program is run in the year 2101, this would cause problems.

Also, I can't always assume that the hardware will return the current year we are living in. This is what my program is actually going to check.

So, say for example packet[0] = 0x02. This would assume the hardware returned the year 2002.

What is the best way to achieve this?

asked on Stack Overflow Jun 21, 2012 by brazc0re • edited Jun 21, 2012 by Joey

2 Answers

int packetyear = year - year % 100 + packet[0];
answered on Stack Overflow Jun 21, 2012 by Joey

You can get the last to decimal digits of the year with the modulo operator:

int systemYearLastTwoDigits = DateTime.Now.Year % 100;

Note that this has nothing to do with the Least Significant Byte of the year, which equals the last to hexadecimal digits of the year.

answered on Stack Overflow Jun 21, 2012 by O. R. Mapper

User contributions licensed under CC BY-SA 3.0