gpt4 book ai didi

c - 如何以人类可读的形式打印无符号整数时间?

转载 作者:行者123 更新时间:2023-11-30 15:22:52 28 4
gpt4 key购买 nike

我有一个原始时无符号整数,我尝试以某种人类可读的形式打印它

uint32_t rawtime=3675431915;
struct tm * timeinfo;
timeinfo = localtime ((const time_t *) &rawtime);
asctime(timeinfo);
printf ("Time and date: %s", asctime(timeinfo));

当我调用 asctime(timeinfo) 时它崩溃了。有人能告诉我如何正确地做到这一点吗?问题是我没有看到任何如何使用无符号整数或整数执行此操作的示例。这个http://www.cplusplus.com/reference/ctime/localtime/仅显示了 time_t 的示例,但从示例中不清楚如何使用 uint32_t 。

注意:还有警告:此十进制常量 (3675431915) 仅在 ISO C90 中无符号

最佳答案

简单地说,由于 sizeof(time_t) 未定义(通常是 48),因此没有将 uint32_t 转换为 time_t 的可移植方法。

例如,一个原因是在 32 位计算机上 time_t 甚至无法保存您在示例中提供的时间戳。

#include <time.h>
#include <stdio.h>
#include <stdint.h>

int
main(int argc, char *argv[]) {
uint32_t rawtime = 3675431915u;

struct tm * timeinfo;
time_t t = rawtime;
// note absence of indirect convert via pointer
// I have no idea, why you wanted to do this, anyway
timeinfo = localtime (&t);
asctime(timeinfo);
printf ("Time and date: %s", asctime(timeinfo));
return 0;
}

将在 64 位 time_t 机器上生成时间和日期:Thu Jun 20 19:18:35 2086,但会生成时间和日期:Mon 1950 年 5 月 15 日 11:50:19 在 32 位机器上。这是因为将 rawtime 转换为有符号整数 time_t 时出现范围溢出。

转换仅在以下假设下有效:time_t 在所有目标平台上都是有符号整数(不保证)。即使在这种情况下,您也应该防止值溢出。

关于c - 如何以人类可读的形式打印无符号整数时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996548/

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