在某些场合需要将时间存储格式压缩到4个字节,在字符串的时间和字节数的格式之间进行一个转换。
短时间存储的格式:
Time(HMS) /*时分秒*/
Bit Position | 0 1 2 3 4 | 5 6 7 8 9 A | B C D E F |
Length(bit) | 5 | 6 | 5 |
Contents | Hours(时) | Minutes(分) | 2-second increments(2秒) |
Value Range | 0–23 | 0–59 | 0-29 in 2-second intervals |
Date(YMD) /*年月日*/
|
总共32个bits,4个字节。
范例:[B3 02 0D 5D]
02B3[年月日] 5D0D[时分秒]--2001年5月19日11时40分26秒
下面就是具体的实现程序:
/******************************
将tm数据转为字节,主要用的就是年月日 时分秒
*******************************/
static void convertDateToBytes(struct tm value, unsigned char buffer[])
{
unsigned char timeBs[6] = {0x00};
timeBs[5] = (unsigned char)(value.tm_year);
timeBs[4] = (unsigned char)(value.tm_mon);
timeBs[3] = (unsigned char)(value.tm_mday);
timeBs[2] = (unsigned char)(value.tm_hour);
timeBs[1] = (unsigned char)(value.tm_min);
timeBs[0] = (unsigned char)(value.tm_sec);
//根据上面的格式转换成字节形式的时间
//年月日的低8位
buffer[0] = (timeBs[4]<<5)+timeBs[3];
//年月日的高8位
buffer[1] = (timeBs[5]<<1)+(timeBs[4]>>3);
//时分秒的低8位,秒0-29
buffer[2] = (timeBs[1]<<5)+(timeBs[0]/2);
//时分秒的高8位
buffer[3] = (timeBs[2]<<3)+(timeBs[1]>>3);
}
/******************************
将字节数据时间转换为tm时间数据
*******************************/
static struct tm convertBytesToDate(unsigned char buffer[])
{
struct tm tt;
unsigned char year = 0;
unsigned char mon = 0;
unsigned char day = 0;
unsigned char hour = 0;
unsigned char min = 0;
unsigned char sec = 0;
//根据上面的格式转换成整数形式的时间
year = (buffer[1]>>1);
mon = ((buffer[1]&0x01)<<3) + ((buffer[0]>>5));
day = buffer[0]&0x1F;
hour = buffer[3]>>3;
min = ((buffer[3]&0x07)<<3) + ((buffer[2]>>5));
sec = (buffer[2]&0x1F)*2;
tt.tm_year = (int)year;
tt.tm_mon = (int)mon;
tt.tm_mday = (int)day;
tt.tm_hour = (int)hour;
tt.tm_min = (int)min;
tt.tm_sec = (int)sec;
printf("%d-%d-%d %d:%d:%d\n", tt.tm_year+1900, tt.tm_mon+1, tt.tm_mday, tt.tm_hour
, tt.tm_min, tt.tm_sec);
return tt;
}