I am trying to convert a char* to double and back to char* again. the following code works fine if the application you created is 32-bit but doesn’t work for 64-bit application. The problem occurs when you try to convert back to char* from int. for example if the hello = 0x000000013fcf7888 then converted is 0x000000003fcf7888 only the last 32 bits are right.
#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;
}
On 64-bit Windows pointers are 64-bit while
intis 32-bit. This is why you’re losing data in the upper 32-bits while casting. Instead ofintuselong longto hold the intermediate result.Make similar changes for the reverse conversion. But this is not guaranteed to make the conversions function correctly because a double can easily represent the entire 32-bit integer range without loss of precision but the same is not true for a 64-bit integer.
Also, this isn’t going to work
That conversion will simply truncate anything digits after the decimal point in the floating point representation. The problem exists even if you change the data type to
unsigned long long. You’ll need toreinterpret_cast<unsigned long long>to make it work.Even after all that you may still run into trouble depending on the value of the pointer. The conversion to
doublemay cause the value to be a signalling NaN for instance, in which cause your code might throw an exception.Simple answer is, unless you’re trying this out for fun, don’t do conversions like these.