c# - Fastest way to serialize the Date portion of a DateTime into 4 bytes? -


i want serialize date portion of datetime 4 bytes (could int32). fastest way so?

background: in order serialize full datetime have been using tobinary method far. returns int64 i'm storing elsewhere. now, have requirement store date part of datetime using half space. so, wondering how achieve in fastest way performance crucial.

options come mind is:

  • encode year, month, day , int yyyymmdd using multiplications , property accesses nice side-effect encoding human-readable.
  • keep using tobinary , keep "the upper or lower half" of returned long. don't know if possible.
  • check how datetime stored internally. maybe date portion can accessed in other ways.

how it?

datetimes stored number of ticks since 00:00:00, january 1, 0001. if take datetime's ticks , divide timespan.ticksperday, end number of days since january 1, 0001.

reverse operation (multiply timespan.ticksperday) when deserializing.

since there "only" 3,652,058 days in range covered datetime, fit in int32

to serialize:

system.datetime toserialize; long longdays = toserialize.ticks / system.timespan.ticksperday;  // safe since (datetime.maxvalue - datetime.minvalue).days << int32.maxvalue int days = (int)longdays;  // serializes `days` serialize other int 

to deserialize:

int days; long ticks = days * system.timespan.ticksperday; system.datetime deserialized = new datetime(ticks); 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -