# [ntp:questions] Re: Calculating NTP timestamp in C program

Brian Inglis Brian.Inglis at SystematicSW.Invalid
Tue Jul 25 10:53:35 UTC 2006

```On 10 Jul 2006 23:11:34 GMT in comp.lang.c.moderated, bg_ie at yahoo.com
wrote:

>Hi,
>
>I wish to write a C program which obtains the system time and hence
>uses this time to print out its ntp equivalent.
>
>Am I right in saying that the following is correct for the seconds part
>of the ntp time?
>
>long int ntp.seconds = time(NULL) + 2208988800;

Yep.

>How might I calculate the fraction part?

The fraction part is an unsigned binary fraction of a second i.e. MSB
== 0.5s so depending on where you get your high resolution time from:

unsigned long ntp.fraction = (double)units/UNITS_PER_S*NTP_PER_S;
where:
#define UNITS_PER_S	1E9 /* or impl defined symbol */
#define NTP_PER_S	4294967296.

but for your time to be meaningful, you need to get your seconds and
fraction counts at the same instant, through a non-standard function,
such as POSIX clock_gettime(), not through a separate call to time().

Note that ntp.seconds should also be an unsigned long; the NTP date is
a signed 128 bit quantity with a 64 bit fraction, but the current NTP
timestamp is truncated to 32 bits each for seconds and fraction.

See:
http://www.cis.udel.edu/~mills/y2k.html#ntp
http://en.wikipedia.org/wiki/Unix_time

--
Thanks. Take care, Brian Inglis 	Calgary, Alberta, Canada

Brian.Inglis at CSi.com 	(Brian[dot]Inglis{at}SystematicSW[dot]ab[dot]ca)