1

我需要从 unix timespec 转换为 NTP 时间戳:纪元,从时代开始的秒数,秒的分数。

NTP时间戳在这里解释:NTP时间戳

这是我的代码。你觉得这样好吗?

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);
}
4

1 回答 1

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$
于 2021-08-05T06:53:13.883 回答