获取时间戳,从十进制转换为16进制(4字节)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
int printf_time(void)
{
time_t timep;
time(&timep);
char *s = ctime(&timep);
printf("date:%s",s);
return 0;
}
int get_time_ms(char *buff, int len)
{
struct timeval tv;
struct tm* ptm;
char time_string[40];
long milliseconds;
if(buff == NULL)
{
printf("%s buff is NULL.\n", __func__);
return -1;
}
gettimeofday(&tv, NULL);
ptm = localtime (&(tv.tv_sec));
strftime (time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm);
milliseconds = tv.tv_usec / 1000;
snprintf (buff, len, "%s.%03ld", time_string, milliseconds);
return 0;
}
void To_Hex(const unsigned int value, char buffer[], int length)
{
unsigned int i=(sizeof(unsigned int)*2);
unsigned int temp;
int j=0;
while(i--)
{
temp = (value&(0xf<<(4*i)))>>(4*i);
if(temp>9)
buffer[j] = 'A'+temp-10;
else
buffer[j] = '0'+temp;
j++;
}
buffer[length] = '\0';
}
int main()
{
char buf_hex[100];
char buff[40];
unsigned int time = 1666020829;
memset(buf_hex,0,sizeof(buf_hex));
To_Hex(time,buf_hex,8);
printf ("time is :%s \n",buf_hex);
get_time_ms(buff, sizeof(buff));
printf("time:%s\n", buff);
printf_time();
memset(buff, 0, 40);
FILE * fd = popen("date +%s" , "r");
fread(buff, 1, 40, fd);
pclose(fd);
printf("popen:%s",buff);
memset(buf_hex,0,sizeof(buf_hex));
To_Hex(atoi(buff), buf_hex, 8);
printf ("popen is :%s \n",buf_hex);
return 0;
}