Convert NTP 64 bits time to UnixTime¶
I was working on a RTP 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.
After googling a lot for a way to transform one Stamp to the other, ended up reading the source for the OpenMash, more specificly, the rtp/ntp-time.h header file.
So, this post try to explain what each of this formats are, and how to convert from the first to the later.
NTP 64 bits¶
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.
Unix TimeStamp¶
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.
Converting NTP 64 Bits to Unix TimeStamp¶
1 my $ntphi=3439021312;
2 my $ntplo=3302649461;
3
4 my $ntpts=$ntphi+$ntplo/4294967296;
5
6 my $uxts=$ntpts-2208988800;
7
8 my $localdate=localtime($uxts);
Explaining the code¶
First, we create the real representation of the NTP TimeStamp, with a integer part of seconds and a decimal part representing parts of seconds.
Then remove the offset (in seconds) between January 1st, 1900 and January 1st, 1970 (2208988800).
This give us the unix timestamp.
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.