太多错误无法列举(尽管你走在了正确的轨道上);这段代码似乎对我有用:
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$