Convert Unix/Linux time to Windows FILETIME

后端 未结 3 852
悲哀的现实
悲哀的现实 2020-12-18 07:23

I am once again going from Windows to Linux, I have to port a function from Windows to Linux that calculates NTP time. Seems simple but the format is in Windows FILETI

3条回答
  •  抹茶落季
    2020-12-18 08:09

    First, why 1601? Because the Gregorian Calendar repeats itself every 400 years, and the proleptic Gregorian Calendar starts with 0001-01-01. So 1601 was the last cycle start before 1980(1970,...) and that simplifies the calculations. (Oh, and that's why the 3rd millenium started on 2001-01-01, and not on 2000-01-01...)

    To create something like a NTP time stamp with a binary fraction from a FILETIME,

    1. Shift the origin of the epoch, using a LONGLONG or ULONGLONG to represent the FILETIME's ticks.
    2. Do a floor division of the ticks by 10^7 to get the seconds (as quotient) and the fraction (as the remainder). If you calculate purely in unsigned, simply divide. But you cannot represent negative values in that case.
    3. Unsigned multiply the fraction (which must be >= 0) in 64 bits by 1844674407371ull, which is 2^64 / 10^7 (rounded)
    4. Take the upper 32 bits of the product as the binary fraction of the NTP time stamp. (You might want to round from the lower 32 bits of the product. Note that a rounding carry into the full seconds cannot occur as long as the fractional ticks are strict below 10^7.)

提交回复
热议问题