NTP64bits2UnixTime

Version 1 (the Mage, Feb 07, 2010 22:43)

1 1
h1. Convert NTP 64 bits time to UnixTime
2 1
3 1
I was working on a "RTP":http://www.ietf.org/rfc/rfc3550.txt related project, recieving Reports, and RTP uses NTP 64 bits timestamps. But those are not very useful for me, so I needed to convert them to UnixTime Stamps.
4 1
5 1
After googling a lot for a way to transform one Stamp to the other, ended up reading the source for the "OpenMash":http://www.openmash.org/, more specificly, the "rtp/ntp-time.h":http://www.openmash.org/lxr/source/rtp/ntp-time.h header file.
6 1
7 1
So, this post try to explain what each of this formats are, and how to convert from the first to the later.
8 1
9 1
h2. NTP 64 bits
10 1
11 1
12 1
The 64 bits NTP TimeStamp is a two double-words value. The high 32 bits represent the seconds from January 1st, 1900 and the second represent the fractions of seconds. NTP 64 bits is a high precision value, capable of represent fraction with 1/4294967296 of second precision.
13 1
14 1
h2. Unix TimeStamp
15 1
16 1
17 1
The Unix TimeStamp represent the number of seconds from January 1st, 1970, and are not usually used to represent smaller than a second time fractions. However, in Perl, you can use the fractional part, but it will be ignored, I think.
18 1
19 1
h2. Converting NTP 64 Bits to Unix TimeStamp
20 1
21 1
<pre><code class="perl">
22 1
my $ntphi=3439021312;
23 1
my $ntplo=3302649461;
24 1
25 1
my $ntpts=$ntphi+$ntplo/4294967296;
26 1
27 1
my $uxts=$ntpts-2208988800;
28 1
29 1
my $localdate=localtime($uxts);
30 1
</code></pre>
31 1
32 1
h2. Explaining the code
33 1
34 1
First, we create the real representation of the NTP TimeStamp, with a integer part of seconds and a decimal part representing parts of seconds.
35 1
36 1
Then remove the offset (in seconds) between January 1st, 1900 and January 1st, 1970 (2208988800).
37 1
38 1
This give us the unix timestamp.
39 1
40 1
Obviously, if you just want the unixtimestamp on a second precision, all you need is the high part of the ntp timestamp (the hi 32 bits part), and to substract the offset.