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 ,
intyyyymmdd using multiplications , property accesses nice side-effect encoding human-readable. - keep using
tobinary, keep "the upper or lower half" of returnedlong. don't know if possible. - check how
datetimestored 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
Post a Comment