首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从unix timespec转换为NTP

从unix timespec转换为NTP
EN

Stack Overflow用户
提问于 2015-04-22 15:39:40
回答 1查看 573关注 0票数 1

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

NTP时间戳的解释如下:NTP Timestamp

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

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2021-08-05 06:53:14

要枚举的错误太多了(尽管您是在正确的轨道上);这段代码似乎适合我:

代码语言:javascript
复制
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$
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29790841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档