I understand that reinterpret_cast may do it, but I think it did not do the data conversion. I don't want to loop over and do them one by one, and wonder whether there is an elegant way to do both the pointer type and data type conversion. Thanks!
1 Answer
If, as I am assuming, you have some float* that points to the first element in an array of floats and you want to use them as ints then I suggest a few options:
If you don't want
float, don't getfloats. Just store an array ofints in the first place.Likewise, if you don't want
ints, then change your code to usefloats throughout.If you do indeed want to have an array of
floats and at some point want to convert them toints, do it when you need it. Usestatic_cast<int>to do the conversion on each element in a safe manner.If you'd like to convert the whole array at once, then I suggest you do something like so:
float float_array[N] = /* ... */; std::vector<int> ints(float_array, float_array + N);Alternatively, if you really want to stick with arrays, use
std::copy:float float_array[N] = /* ... */; int int_array[N]; std::copy(float_array, float_array + N, int_array);The
std::vectorabove is much preferred, however.
reinterpret_castis definitely not the way to do it.