Justin Tanner - 1 year ago 84
C Question

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

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

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

What is the smallest data structure possible?

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`.]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download