gpt4 book ai didi

c++ - 将 FILETIME 转换为可移植时间单位

转载 作者:可可西里 更新时间:2023-11-01 11:07:24 28 4
gpt4 key购买 nike

我将如何转换 Windows FILETIME将对象转换为 time_t 或原始秒/毫秒?我正在将一些代码从 Windows 移植到 Unix,因此我不能依赖 Windows API 函数。

最佳答案

FILETIME 定义为

Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

因此,要将其转换为 Unix 时间,只需减去两个纪元时间并将 100 纳秒间隔转换为秒/毫秒即可。任何数量的工具/站点都会告诉您这两个纪元相隔 134774 天(或 11644473600 秒)。因此:

void convert_filetime(struct timeval *out_tv, const FILETIME *filetime)
{
// Microseconds between 1601-01-01 00:00:00 UTC and 1970-01-01 00:00:00 UTC
static const uint64_t EPOCH_DIFFERENCE_MICROS = 11644473600000000ull;

// First convert 100-ns intervals to microseconds, then adjust for the
// epoch difference
uint64_t total_us = (((uint64_t)filetime->dwHighDateTime << 32) | (uint64_t)filetime->dwLowDateTime) / 10;
total_us -= EPOCH_DIFFERENCE_MICROS;

// Convert to (seconds, microseconds)
out_tv->tv_sec = (time_t)(total_us / 1000000);
out_tv->tv_usec = (useconds_t)(total_us % 1000000);
}

关于c++ - 将 FILETIME 转换为可移植时间单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878395/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com