+ 1

Converting address to int

So the goal was to convert a hexadecimal address to a decimal int but i get an error along the lines of loses precision could someone explain why what im doing isnt possible yet int x = 0xff is? Code: #include <iostream> using namespace std; struct Test{ Test* data = this; int key = (int)data; }; int main() { Test l; cout<<&l<<"\n"<<l.data<<"\n"<<l.key; return 0; }

14th Mar 2019, 11:36 AM
frank
frank - avatar
1 Réponse
+ 6
sizeof(Test*) gives 8 bytes, while sizeof(int) gives 4. You are trying to cast a value represented using 8 bytes, to a container which stores 4 bytes. The compiler does not allow you to do so and will warn you of lossy conversion. Instead, try using intptr_t, which is 8 bytes in size. struct Test{ Test* data = this; int key = (intptr_t)data; }; int main() { Test l; cout<<&l<<"\n"<<l.data<<"\n"<<l.key; return 0; } intptr_t ref: http://www.cplusplus.com/reference/cstdint/
14th Mar 2019, 11:57 AM
Hatsy Rei
Hatsy Rei - avatar