Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert a 16-bit short array to a 32-bit int array?

Tags:

c++

arrays

c

copy

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)?

like image 656
Vladimir Avatar asked Sep 06 '11 13:09

Vladimir


2 Answers

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.

like image 152
Konrad Rudolph Avatar answered Oct 14 '22 21:10

Konrad Rudolph


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; }
like image 44
Nawaz Avatar answered Oct 14 '22 19:10

Nawaz