可以存储时间戳的最小字节数是多少? [英] What is the smallest number of bytes that can store a timestamp?

查看:41
本文介绍了可以存储时间戳的最小字节数是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 C 创建我自己的时间戳数据结构.

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

天 (0 - 31)、小时 (0 - 23)、分钟 (0 - 59)

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

最小的数据结构是什么?

What is the smallest data structure possible?

推荐答案

好吧,你可以把它全部打包成一个 unsigned short(即 2 个字节,天 5 位,小时 5 位,分钟 6 位)...并使用一些移位和掩码来获取值.

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); 

或使用宏

#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).

[编辑:使用 unsigned short - 未签名的 short.]

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

这篇关于可以存储时间戳的最小字节数是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆