Skip to content

Instantly share code, notes, and snippets.

@brihter
Created June 29, 2015 08:27
Show Gist options
  • Save brihter/be667911a865e55c347a to your computer and use it in GitHub Desktop.
Save brihter/be667911a865e55c347a to your computer and use it in GitHub Desktop.
compresses datetime into 2 bytes
// represent the full date w/ 16 bits (2 bytes)
//
// d - day
// m - month
// y - year
//
/// format:
// d d d d d | m m m m | y y y y y y y
//
// 5 bits to represent the day - 2^5 = 32
// 4 bits to represent the month - 2^4 = 16
// 7 bits to represent the year - 2^7 = 128, we use only the last 2 digits
// and support the year range from 2000 to 2099
var b_year = new BitArray(7);
var b_mnth = new BitArray(4);
var b_days = new BitArray(5);
var b_dt = new BitArray(16);
var dates = new List<DateTime>
{
DateTime.Now,
DateTime.Now.AddYears(7),
DateTime.Now.AddYears(-4)
};
byte i = 0, offset = 0;
byte[] bytes = new byte[4];
BitArray bits = null;
foreach (var dt in dates)
{
// clear
b_dt.SetAll(false);
b_days.SetAll(false);
b_mnth.SetAll(false);
b_year.SetAll(false);
// convert days to 5-bit array
bytes = BitConverter.GetBytes(dt.Day);
bits = new BitArray(bytes);
for (i = 0; i < 8; ++i)
{
if (i == b_days.Length)
break;
b_days.Set(i, bits[i]);
}
// convert months to 4-bit array
bytes = BitConverter.GetBytes(dt.Month);
bits = new BitArray(bytes);
for (i = 0; i < 8; ++i)
{
if (i == b_mnth.Length)
break;
b_mnth.Set(i, bits[i]);
}
// convert years to 7-bit array
bytes = BitConverter.GetBytes(Convert.ToByte(dt.Year.ToString().Substring(2, 2)));
bits = new BitArray(bytes);
for (i = 0; i < 8; ++i)
{
if (i == b_year.Length)
break;
b_year.Set(i, bits[i]);
}
// glue together
for (i = 0; i < b_days.Length; ++i)
b_dt.Set(i, b_days[i]);
offset = i;
for (i = 0; i < b_mnth.Length; ++i)
b_dt.Set(i + offset, b_mnth[i]);
offset = i;
for (i = 0; i < b_year.Length; ++i)
b_dt.Set(i + offset, b_year[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment