0

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!

7
  • 2
    We need more scope to this. That alone sounds like a bad idea. Commented Nov 29, 2012 at 20:05
  • 1
    reinterpret_cast is definitely not the way to do it. Commented Nov 29, 2012 at 20:07
  • What is purpose for conversion? Commented Nov 29, 2012 at 20:08
  • Hi, could explain what you mean by "We need more scope to this"? Commented Nov 29, 2012 at 20:09
  • Create a SSCC(C)E -- sscce.org -- that describes what you want to do. It should compile, even if there is a step you don't understand. Describe what the more general problem is that you want to solve -- provide some context to the short self contained example as well. Commented Nov 29, 2012 at 20:11

1 Answer 1

3

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:

  1. If you don't want float, don't get floats. Just store an array of ints in the first place.

  2. Likewise, if you don't want ints, then change your code to use floats throughout.

  3. If you do indeed want to have an array of floats and at some point want to convert them to ints, do it when you need it. Use static_cast<int> to do the conversion on each element in a safe manner.

  4. 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);
    
  5. 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::vector above is much preferred, however.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answers! Apparently I don't want to use 3. My scenario is convert a float array to an int array, and load this int array to GPU. I am not sure the GPU API will take STL object or not, so I may need to do 5. However, if the STL vector can be easily converted or casted to a regular array, maybe I can do it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.