【问题标题】:Convert from unix timespec to NTP从 unix timespec 转换为 NTP
【发布时间】:2015-06-29 17:08:17
【问题描述】:

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

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

【问题讨论】:

  • 时代不在时间戳中,是它的超集

标签: ntp qnx qnx-neutrino timespec


【解决方案1】:

错误太多,无法一一列举(不过你的思路是对的);这段代码似乎对我有用:

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$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多