C - 时间值到 uint64_t

标签 c timeval

早晨!

我正在尝试从 timeval 结构中获取纳秒时间戳 (uint64_t)。

    struct timeval t;
    // initialized so that ....
    print("t sec: %ld, micro sec: %ld", t.tv_sec, t.tv_usec);
    // .... prints "t sec: 4, micro sec: 130728"

    long int sec = (long int) t.tv_sec;
    // just did that because I thought that using time_t in calculations may cause errors
    // print("%ld", sec) -> 4, so this seems to work as expected    

    uint64_t t_int = (sec * 1000000 + t.tv_usec) * 1000; // should be nanoseconds
    print("t_int (uint64_t) %llu", t_int);
    // prints "t_int (uint64_t) 18446744073545312320"

我的时间值绝对应该适合 uint64_t。此外,从 time_t 到 long int 的强制转换有效,所以我所做的只是用两个 long int 进行简单计算,将结果放入 uint64_t,所以我不确定为什么我得到一个明显错误的值。有任何想法吗?这只是一种错误的格式化方式(使用 %llu)吗?

最佳答案

任何一个:

uint64_t t_int = ((uint64_t)t.tv_sec * 1000000 + t.tv_usec) * 1000;

或者:
uint64_t t_int = (t.tv_sec * 1000000ULL + t.tv_usec) * 1000;

后者跳过强制转换,而是通过使用 * 的右侧操作数来执行提升。已经是至少 64 位的类型(而不是将左侧转换为 1)。要么有效;这是你喜欢什么风格的问题。

不要通过类型为 long 的临时变量像你一样。 long可能是 32 位类型,不适合 2038 年 1 月之后的时间。如果您需要临时变量,请使用 time_tint64_t或类似。但它不是必需的。

您也可以考虑使用 int64_t (并将 ULL 更改为 LL )而不是 uint64_t ,以便您可以表示 1970 年之前的时间。

关于C - 时间值到 uint64_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61346439/

相关文章:

c++ - 时间不匹配

c - 在 C 中使用堆栈

c - 如何使用循环缓冲区将信号移动 90 度

c - 有没有一种标准方法可以将 struct timeval 转换为 struct timespec?

c# - 将 timeval 结构转换为 c#

c - getrusage 是如何工作的以及 usage 结构内部到底是什么?

c - scanf 格式字符串中的非空白字符

c - 通过指针传递值

c - 为什么 gprofile 配置文件中的 main 调用不止一次?

c++ - 在 C/C++ 中将月/日/年/时间转换为时间值