从 double 转换为 unsigned int 时的 C++ 整数溢出问题

标签 c++ datetime time casting type-conversion

我需要在 C++ 中将时间从一种格式转换为另一种格式,并且它必须跨平台兼容。我创建了一个结构作为我的时间容器。结构字段也必须是遗留代码指定的 unsigned int

struct time{   
unsigned int timeInteger;   
unsigned int timeFraction;
} time1, time2;

从数学上讲,转换如下:

time2.timeInteger = time1.timeInteger + 2208988800

time2.timeFraction = (time1.timeFraction * 20e-6) * 2e32

这是我在 C++ 中的原始代码,但是当我尝试写入二进制文件时,转换后的时间与真实数据不匹配。我认为这个问题是由于类型转换错误造成的?此代码将在 VS2008 中编译并执行。

void convertTime(){
   time2.timeInteger  = unsigned int(time1.timeInteger + 2209032000);
   time2.timeFraction = unsigned int(double(time1.timeFraction) * double(20e-6)*double(pow(double(2),32)));
}

最佳答案

只是一个猜测,但您是否假设 2e32 == 2^32?如果您尝试将结果缩放为 32 位整数,则此假设是有意义的。事实上 2e32 == 2 * 10^32

关于从 double 转换为 unsigned int 时的 C++ 整数溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118927/

相关文章:

c++ - v4l2 很简单的例子

c - C 中的时间函数始终显示 "Wed Dec 31 23:59:59 1969"

python - 在 python 日期时间中处理月份

java - 我希望日期以毫秒(纪元)格式显示,但使用时间戳获取日期

java - 数字 "41794"和今天的日期(即 04/06/2014)之间有什么关系?

windows - 以毫秒为单位的打印批处理时间

c++ - Bitblt,createdibsection,图像损坏

c++ - 我可以访问嵌套模板 C++ 的类型吗

c++ - 为模板类中的嵌套类专门化 std::hash

C++ boost 在 UTC 中获取 unix 时间戳