【发布时间】:2011-09-26 20:21:19
【问题描述】:
我正在尝试将 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;
}
【问题讨论】:
-
这些转换既无用又危险(仅将 指针 转换为浮点数的想法就让我感到畏缩)。你应该避开它们。
-
@user965772 你为什么要这样做?
-
当你理解它时,铸造就足够危险了......
-
尤其是 unsigned int convert_int = (unsigned int)hello_to_double;我认为是毁灭的秘诀。对于足够大的整数 int 来加倍到 int 不会以您开始的数字结尾(它与浮点运算有关)
标签: c++ visual-c++ win32ole