Home > OS >  How is date encoded/stored in MySQL?
How is date encoded/stored in MySQL?

Time:03-21

I have to parse date from raw bytes I get from the database for my application on C . I've found out that date in MySQL is 4 bytes and the last two are month and day respectively. But the first two bytes strangely encode the year, so if the date is 2002-08-30, the content will be 210, 15, 8, 31. If the date is 1996-12-22, the date will be stored as 204, 15, 12, 22. Obviously, the first byte can't be bigger than 255, so I've checked year 2047 -- it's 255, 15, and 2048 -- it's 128, 16.

At first I thought that the key is binary operations, but I did not quite understand the logic:

2047: 0111 1111 1111
255:  0000 1111 1111
15:   0000 0000 1111

2048: 1000 0000 0000
128:  0000 1000 0000
16:   0000 0001 0000

Any idea?

CodePudding user response:

It seems that the logic of encoding is to erase the most significant bit of the first number and to write the second number from this erased bit like this:

2002 from 210 and 15:

1101 0010 -> _101 0010;
0000 1111   _101 0010 -> 0111 1101 0010

2048 from 128 and 16:

1000 0000 -> _000 0000
0001 0000   _000 0000 -> 1000 0000 0000

CodePudding user response:

Based on what you provide, it seems to be N1 - 128 N2 * 128.

  • Related