Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a date with two bytes

I recently saw a talk about binary encoding and the example given was storing the date part (day, month and year) of a Java Date object in two bytes. I'm now trying to understand the code snippet from the talk:

long time = new Date().getTime();  // time in ms since epoch
time /= 86400000; // ms in a day
byte a = (byte)(time >>> 8);
byte b = (byte)(time);

Now the bit I'm missing is how it's apparently "simple" to turn these two bytes back into the day, month and year of the original date. I'm also not sure why we use two bytes if we retain the original time values as a byte as well.

Could someone please explain how that is possible? I understand what the code above is doing, just not how it's possible to restore the original date.

Update

This is the talk, the slide in question is 20/21

http://www.slideshare.net/jtdavies/turn-your-xml-into-binary-java-one-2014

like image 397
imrichardcole Avatar asked May 18 '26 11:05

imrichardcole


1 Answers

Here is how to restore the date from the bytes:

long time = new Date().getTime(); // time in ms since epoch
time /= 86400000; // ms in a day
byte a = (byte) (time >>> 8);
byte b = (byte) (time);

time = a;
time = time << 8;
time = time | b;
time *= 86400000;

System.out.println(new Date(time));

But, unfortunately, this will not always work, as days are not always 86400000 ms long, due to daylight savings and leap seconds.

like image 96
Florent Bayle Avatar answered May 20 '26 23:05

Florent Bayle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!