从unix timespec转换为NTP

时间:2015-04-22 07:39:40

标签: ntp qnx qnx-neutrino timespec

我需要将unix timespec转换为NTP时间戳:Epoch,从时代开始的秒数,秒的一小部分。

此处解释了NTP时间戳:NTP Timestamp

这是我的代码。你认为这样可以吗?

void unix_ns_2ntp(struct ntp_time *ntp, const struct timespec *ts)
{
    uint64_t era_and_offset = ((uint64_t)tv->tv_sec) + ((uint64_t)UNIX_NTP_OFFSET);
    uint32_t era = era_and_offset>>32;
    ntp->hi = (uint32_t)(era_and_offset);
    ntp->lo = (uint32_t)((double)ts->tv_nsec * (double)(1LL<<32) * 1.0e-9);
}

1 个答案:

答案 0 :(得分:0)

太多的错误无法一一列举(不过你是在正确的轨道上);这段代码似乎对我有用:

Mac_3.2.57$cat testNtpTimeConvert3.c
// ref.: https://stackoverflow.com/questions/29790841/convert-from-unix-timespec-to-ntp

#include <stdio.h>

// ref.: CC38EC6A.8FCCA1C4 (10:10:02.561 JST Tue Jul 29 2008)
//                        = 01:10:02.561 UTC Tue Jul 29 2008

// from https://www.eecis.udel.edu/~mills/leap.html
// 31 Dec 98 23:59:59 translated to seconds since 1900 minus
// 31 Dec 98 23:59:59 translated to seconds since 1970 gives
// the UTC to NTP offset
unsigned long UNIX_NTP_OFFSET = 3124137599 - 915148799;

struct ntp_time {
    unsigned int high;
    unsigned long low;
};

struct timespec {
    unsigned int tv_sec;    
    unsigned long tv_nsec;
};    

void unix_ns_2ntp(struct ntp_time *ntp, const struct timespec *ts) {
    ntp->high = ts->tv_sec + UNIX_NTP_OFFSET;

    // convert from nanosecs to secs and then to 2^-32 secs
    // (must do in reverse to avoid underflow)
    ntp->low = (ts->tv_nsec * 4294967296 / 1000000000);
}

int main(void) {
    struct timespec ts;
    struct ntp_time ntp;
    ts.tv_sec = 1217293802; // 10:10:02.561 JST Tue Jul 29 2008 = 01:10:02.561 JST Tue Jul 29 2008
    ts.tv_nsec = 561000000;
    unix_ns_2ntp(&ntp, &ts);
    printf("%08.8X.%08.8lX\n", ntp.high, ntp.low);

    // since we only got 3 decimal digits of precision in this test example,
    // we only expect (log 1000 / log 2)[bits]/4[bits/char] ~=
    // 2.5 (2 or 3) hex chars of precision\n");
    printf("CC38EC6A.8FCCA1C4?\n");

    return(0);
}
Mac_3.2.57$cc testNtpTimeConvert3.c
Mac_3.2.57$./a.out 
CC38EC6A.8F9DB22D
CC38EC6A.8FCCA1C4?
Mac_3.2.57$