gpt4 book ai didi

c++ - C++ 中的 Matlab 类型转换

转载 作者:行者123 更新时间:2023-11-28 00:09:48 27 4
gpt4 key购买 nike

我正在尝试用 C++ 编写 Matlab 类型转换函数。在 Matlab 中它是这样的:

>> format long e
>> d=typecast(uint32([65304 47886]), 'double')

d =

1.016138904784275e-309

HEX 为

0000bb0e0000ff18

在C++中,我做到了这一点

double d = 65304+ ((uint64_t)47886<<32);
std::cout << "d " << "is " << d << std::endl;

d is 2.05669e+14

在十六进制中是 0000bb0e0000ff18

那么,为什么我会得到不同的值?

最佳答案

您并没有真正对结果进行类型转换,您只是在进行类型转换,因此您获得的 double 值与整数值相同。

如果你想做一个真正的typecast与在 MATLAB 中一样,您需要执行以下操作:

unsigned long i = 65304 + ((uint64_t)47886<<32);
// Make the double pointer address the same memory as the integer
double *d = (double *)&i;
std::cout << "d " << "is " << *d << std::endl;

问题是您将遇到可移植性问题,因为此解决方案要求 int 类型中的位数恰好等于 float 类型中的位数。

结果(在我的机器上):

d is 1.01614e-309

关于c++ - C++ 中的 Matlab 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33753299/

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