Efficient way of representing Date

What is an efficient way of representing date?

Try the following code (Taken from Art of Computer Programming Vol 4)

var y = 2012; // Year 2012
var m = 6 // June
var d = 30 // 30th day on the calendar month


// Efficient representation (packing)
var result = (((y << 4) + m) << 5) + d;


Breaking this down further, we have

(y << 4)
Binary representation for 2012 is : 11111011100
Left shift by 4 : 111110111000000

Next we have,

((y << 4)+ m

111110111000000 + 110 (m = 6) = 111110111000110
Left shift 5, becomes 11111011100011000000

Next we add the days to it which bring us to the following equation

11111011100011000000 + 11110 = 11111011100011011110 ( Decimal : 1030366)

So our final result is : 1030366

// Unpacking
var day = result%32;

1030366 % 32 = 30 (once you have this, the rest is pretty straight forward)


var month = (result >> 5) %16;
var year = result >> 9;

Is there any other alternative for doing this? Maybe for other data types such as telephone.

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm