Casting int64_t * to uint64_t *

The signed integer pointer is the output of of a std::vector<int64_t> some_vector, but I know all the values are positive and I want to cast that integer to an unsigned integer. How can I do that and "reinterpret" the vector values as unsigned?

>Solution :

You can simply cast the pointer to the desired type and I think this will almost always work:

uint64_t * data = (uint64_t *);

However I am not sure if this is allowed or safe according to the C++ standard. (Search for "strict aliasing" to learn about one type of pitfall.) And someone will probably tell you there is a better type of cast you can use.

It would be much safer to just leave the type of the pointer as it is, and then when you have an actual int64_t value you can implicitly convert it to a uint64_t or cast it.

int64_t * data = ...;
uint64_t x = data[1];

Leave a Reply