You can static_cast
from an int
to an unsigned
, which performs the appropriate conversion. But what you have is a pointer; this pointer points to a region of memory that is to be interpreted as an int
. Dereferencing the pointer yields the int
's value. static_cast
will not convert between pointers to unrelated types.
int i = 0;
int* ip = &i;
int j = *ip; // treat the region pointed to as an int
To treat the memory as unsigned
under dereference, you need to reinterpret the memory; that's what reinterpret_cast
does.
int i = 0;
int* ip = &i;
unsigned j = *reinterpret_cast<unsigned*>(ip); // treat the region pointed to as unsigned
You shouldn't do this, however. reinterpret_cast
does exactly what it says: reinterprets the memory as a different type. If the bit pattern doesn't match what would be expected for that type, the result will differ from the conversion performed by static_cast<unsigned>
. This can be the case on a system where signed integers are not represented using 2's complement, for instance.
The correct approach is to dereference the int*
then static_cast<unsigned>
the result of that:
int i = 0;
int* ip = &i;
unsigned j = static_cast<unsigned>(*ip); // treat the region pointed to as int
// then convert the int to unsigned
To summarise: static_cast
will perform the integer conversion, but it won't re-interpret a memory region as a different type. That's what reinterpret_cast
is for.