Home > Net >  Converting arrays ushort[] to int[] using Buffer.BlockCopy
Converting arrays ushort[] to int[] using Buffer.BlockCopy

Time:11-08

I'm trying to convert array type of ushort[4k*4k] of values 0-65k to similiar array type of int[] of same values.

It seems to mee that Buffer.BlockCopy is the fastest way to do that. I'm trying the following code:

   ushort[] uPixels = MakeRandomShort(0, 65000, 4000 * 4000);// creates ushort[] array
   int[] iPixels = new int[4000 * 4000];

   int size = sizeof(ushort);
   int length = uPixels.Length * size;
   System.Buffer.BlockCopy(uPixels, 0, iPixels, 0, length);

But iPixels stores some strange values in very strange range -1411814783, - 2078052064, etc.

What is wrong, and what I need to do to make it work properly?

thanks!

CodePudding user response:

There is a related discussion on GitHub.

To copy an ushort[] to an int[] array does not work with a routine tuned for contiguous memory ranges.

Basically, you have to clear the upper halves of the target int cells. Then, some sort of (parallelized?) loop is needed to copy the actual data.

It could be possible to use unsafe code with pointers advanced in steps of two bytes. The implementation of Buffer.BlockCopy is not visible in the Microsoft source repository. It might make sense to hunt for the source and modify it.

  • Related