Home > Net >  Casting int64_t * to uint64_t *
Casting int64_t * to uint64_t *

Time:06-23

The signed integer pointer is the output of some_vector.data() 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?

CodePudding user response:

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

uint64_t * data = (uint64_t *)some_vector.data();

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];

CodePudding user response:

Cast the values when you access them, there is no need to cast the whole vector.

  •  Tags:  
  • c
  • Related