Home > Net >  How to construct a 2 bytes or short from DateTime.Now.Date only value? YYYYmmDD
How to construct a 2 bytes or short from DateTime.Now.Date only value? YYYYmmDD

Time:05-21

I see some guys do following to store Date to 2 bytes only (ushort)!, not 4 bytes (int)

Assume that format yyyyMMdd: 20220521, Fit into 1 short and 1 byte. or 1 integer only. But next code I just copied it from decompiled source. (Not understand how he manipulate bits....)

In my opinion. It can be 1 byte for last digit of year (2022 will stored as 22 byte) 1 short for month, day.... But I failed to make it just 2 bytes like below example.

I don't even understand how they achieve it... I don't understand how next code works. Wish to understand how he think to do that...

   private byte[] PackDate16(DateTime date)
        {
            if (date.Year < 2000 || date.Year > 2127)
                throw new Exception("Invalid year for a 16-bit date. Allowed values are 2010-2127");
            ushort num = (ushort)(date.Year - 2000 << 9 | date.Month << 5 | date.Day);
            return new byte[2]
            {
        (byte) ((uint) num & (uint) byte.MaxValue),
        (byte) ((uint) num >> 8)
            };
        }

After do some search... I found https://bytes.com/topic/net/answers/661377-c-program-convert-2-byte-time-2-byte-date-datetime

Are there any Bit library to do that easily?

CodePudding user response:

Why don't you manipulate with bits at all if you can just add and subtract days?

private static short CompressMe(DateTime value, DateTime minDate) =>
  (short)((value - minDate).Days   short.MinValue);

private static DateTime DeCompressMe(short value, DateTime minDate) =>
  minDate.AddDays(value - short.MinValue); 

For Instance:

DateTime minDate = new DateTime(2000, 1, 1);

// -24592
var result = CompressMe(new DateTime(2022, 5, 21), minDate);
// 6 June 2179
DateTime maxDate = DeCompressMe(short.MaxValue, minDate);

So far so good you can represent dates as short if they in

1 Jan 2000 .. 6 Jun 2179

period

  • Related