What is the most efficient way to convert an array of unsigned short numbers (16 bits per value) into an array of unsigned ints numbers (32 bits per value)?
Copy it.
unsigned short source[]; // …
unsigned int target[]; // …
unsigned short* const end = source + sizeof source / sizeof source[0];
std::copy(source, end, target);
std::copy
internally choses the best copying mechanism for given input types. In this case, however, there’s probably no better way than copying the elements individually in a loop.
Use std::copy
in C++:
#include<algorithm> //must include
unsigned short ushorts[M]; //where M is some const +ve integer
unsigned int uints[N]; //where N >= M
//...fill ushorts
std::copy(ushorts, ushorts+M, uints);
And in C, use manual loop (in fact, you can use manual loop both in C and C++):
int i = 0;
while( i < M ) { uints[i] = ushorts[i]; ++i; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With