Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the smallest number of bytes that can store a timestamp?

Tags:

c

timestamp

I want to create my own time stamp data structure in C.

DAY ( 0 - 30 ), HOUR ( 0 - 23 ), MINUTE ( 0 - 59 )

What is the smallest data structure possible?

like image 830
Justin Tanner Avatar asked Feb 27 '09 18:02

Justin Tanner


People also ask

How many bytes is a timestamp?

The internal representation of a timestamp is a string of between 7 and 13 bytes. Each byte consists of 2 packed decimal digits. The first 4 bytes represent the date, the next 3 bytes the time, and the last 0 to 6 bytes the fractional seconds.

How many bytes does a date time take?

DATETIME: Eight bytes: A four-byte integer for date packed as YYYY×10000 + MM×100 + DD and a four-byte integer for time packed as HH×10000 + MM×100 + SS.


2 Answers

Well, you could pack it all in an unsigned short (That's 2 bytes, 5 bits for Day, 5 bits for hour, 6 bits for minute)... and use some shifts and masking to get the values.

unsigned short timestamp = <some value>; // Bits: DDDDDHHHHHMMMMMM

int day = (timestamp >> 11) & 0x1F;
int hour = (timestamp >> 6) & 0x1F;
int min = (timestamp) & 0x3F;

unsigned short dup_timestamp = (short)((day << 11) | (hour << 6) | min); 

or using macros

#define DAY(x)    (((x) >> 11) & 0x1F)
#define HOUR(x)   (((x) >> 6)  & 0x1F)
#define MINUTE(x) ((x)         & 0x3F)
#define TIMESTAMP(d, h, m) ((((d) & 0x1F) << 11) | (((h) & 0x1F) << 6) | ((m) & 0x3F)

(You didn't mention month/year in your current version of the question, so I've omitted them).

[Edit: use unsigned short - not signed short.]

like image 191
Daniel LeCheminant Avatar answered Oct 25 '22 15:10

Daniel LeCheminant


Do you mean HOUR 0-23 and MINUTE 0-59? I've heard of leap seconds but not leap minutes or hours.

(log (* 31 60 24) 2)
=> 15.446

So you can fit these values 16 bits, or 2 bytes. Whether this is a good idea or not is a completely different question.

like image 37
Ken Avatar answered Oct 25 '22 17:10

Ken