欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

把时间戳转换成16进制BCD码或字符串(直接复制黏贴即可)

程序员文章站 2022-05-02 15:07:25
...

把时间戳转换成16进制BCD码:

1518335905转换成0x20180211155825或"20180211155825"

亲测可直接使用

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
//------------------------------------------------------------------
//strlen个16进制字符串转strlen/2个HEX
//"123456AB"->0x123456AB
//------------------------------------------------------------------
void StringToHex(unsigned char *str,int strlen,unsigned char *data)
{
	int i,j=0;

	for(i=0;i<strlen/2;i++)
	{
		j = str[i*2]-0x30;
		if(j>9)j -= 7;
		data[i] = j*16;

		j = str[i*2+1]-0x30;
		if(j>9)j -= 7;
		data[i] += j;
	}
}
//------------------------------------------------------------------
//datalen个16进制HEX转(strlen*2)个字符串
//0x123456AB->"123456AB"
//------------------------------------------------------------------
void HexToString(unsigned char *data,int datalen,unsigned char *str)
{
	int i;

	for(i=0;i<datalen;i++)
	{
		str[i*2]=data[i]/16+0x30;
		if(str[i*2]>0x39)str[i*2]+=7;
		str[i*2+1]=data[i]%16+0x30;
		if(str[i*2+1]>0x39)str[i*2+1]+=7;
	}
}
//------------------------------------------------------------------
//将时间戳转换为7字节BCD
//------------------------------------------------------------------
int Convert_timestamp_BCD(time_t timestamp,unsigned char *time)
{
    struct tm * timeinfo;
    unsigned char tmptime[20]={0};

    timeinfo = localtime(×tamp);
    strftime(tmptime, 20, "%Y%m%d%H%M%S", timeinfo);
    printf("tmptime = %s \n",tmptime);
    StringToHex(tmptime,14,time);
    return 0;
}
int main(void)
{
    time_t curtime;
    unsigned char time[7]={0};
    unsigned char timestring[15]={0};

    curtime = 1518335905;
    Convert_timestamp_BCD(curtime,time);
    HexToString(time,7,timestring);
    printf("timestring = %s \n",timestring);

    return 0;
}

运行结果:

把时间戳转换成16进制BCD码或字符串(直接复制黏贴即可)

相关标签: 时间戳