char*再次加倍并返回char*(64位应用程序)

int*_*80h 1 c++ win32ole visual-c++

我试图将char*转换为double并再次转换为char*.如果您创建的应用程序是32位但不适用于64位应用程序,则以下代码可以正常工作.当您尝试从int转换回char*时会发生此问题.例如,如果hello = 0x000000013fcf7888然后转换为0x000000003fcf7888,则只有最后32位是正确的.

#include <iostream>
#include <stdlib.h>
#include <tchar.h>
using namespace std;


int _tmain(int argc, _TCHAR* argv[]){

    char* hello = "hello";
    unsigned int hello_to_int = (unsigned int)hello;
    double hello_to_double = (double)hello_to_int;

    cout<<hello<<endl;
    cout<<hello_to_int<<"\n"<<hello_to_double<<endl;

    unsigned int converted_int = (unsigned int)hello_to_double;
    char* converted = reinterpret_cast<char*>(converted_int);

    cout<<converted_int<<"\n"<<converted<<endl;

    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 6

在64位Windows上,指针是64位而int32位是指针.这就是您在投射时丢失高32位数据的原因.而不是int使用long long保存中间结果.

char* hello = "hello";
unsigned long long hello_to_int = (unsigned long long)hello;
Run Code Online (Sandbox Code Playgroud)

对反向转换进行类似的更改.但是这并不能保证转换功能正常,因为double可以很容易地表示整个32位整数范围而不会丢失精度,但对于64位整数则不然.

此外,这不会起作用

unsigned int converted_int = (unsigned int)hello_to_double;
Run Code Online (Sandbox Code Playgroud)

该转换将简单地截断浮点表示中小数点后的任何数字.即使您将数据类型更改为,问题仍然存在unsigned long long.你需要reinterpret_cast<unsigned long long>让它发挥作用.

即便如此,根据指针的值,您仍可能遇到麻烦.例如,转换为double可能导致值为信令NaN,导致您的代码可能抛出异常.

简单的答案是,除非你是为了好玩而尝试这个,否则不要做这样的转换.