# CC portable algorithm to convert time stamp to 8 chars? <->

#### Spartrekus

Hello,

I would glad to make my time stamp string smaller, for windows, bsd,... 8 chars would be ok.
The simple, universal, tiny, algorithm shall convert back and forth (<->) the time stamp <-> 8 chars.

some basic starting point:
Code:
``````char *strtimestamp()
{
long t;
struct tm *ltime;
time(&t);
ltime=localtime(&t);
char charo[50];  int fooi ;
fooi = snprintf( charo, 50 , "%04d%02d%02d%02d%02d%02d",
1900 + ltime->tm_year, ltime->tm_mon +1 , ltime->tm_mday,
ltime->tm_hour, ltime->tm_min, ltime->tm_sec
);

size_t siz = sizeof charo ;
char *r = malloc( sizeof charo );
return r ? memcpy(r, charo, siz ) : NULL;
}``````

Hi Spartrekus,
The simple, universal, tiny, algorithm shall convert back and forth (<->) the time stamp <-> 8 chars.

If I have understood correctly, maybe something like this:

Code:
``````#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define T0 1500000000   /* Fri Jul 14 04:40:00 2017 */

/*
* We can represent every 32bit number using 8 (hex) digits:
* [log(2^32 - 1) / log(16)] = 8
* Using offsets from T0, we can use 8 char (32bit) timestamps until
* Mon Aug 20 11:08:15 2153 if the future machine uses an unsigned 32bit
* integer for time_t or a (signed) 64bit integer.
*/

char *
strtimestamp()
{
char *buf;
time_t delta = time(NULL) - T0;

if ((buf = malloc(9)) != NULL)
(void)sprintf(buf, "%08x", (unsigned int)delta);
return (buf);
}

time_t
timestamptotime(const char *ts)
{
return ((time_t)(strtol(ts, NULL, 16) + T0));
}

int
main(int ragc, char *argv[])
{
char *ts = strtimestamp();
time_t t;

if (ts == NULL)
return (EXIT_FAILURE);
t = timestamptotime(ts);
(void)printf("Timestamp: %s\n", ts);
(void)printf("Date: %s", ctime(&t));

return (EXIT_SUCCESS);
}``````

Last edited: