convert short[] to ushort[]

3.5k Views Asked by At

I need to convert short[] to ushort[] in C#

public ushort[] Pixels16bits;

 GrayscalePixelDataS16 Pixeldata = PixelDataFactory.Create(img.PixelData, 0) as GrayscalePixelDataS16; //Pixeldata has short[] values

Pixels16bits = pixeldata; //Here's where I struggle, I need to convert to ushort prior to assign to pixels16bits

Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

I see a couple options:

img.PixelData.Cast<ushort>().ToArray();

Or perhaps:

img.PixelData.Select(Convert.ToUInt16).ToArray();

Both take advantage of LINQs ability to apply a transform function to a collection.

1
On

As normal solution I recommend:

unsigned = ConvertAll(signed, i => (ushort)i)

This produces less garbage than LINQ solutions while being similarly concise and readable.

A good old fashioned loop is also a consideration, since it allows you to convert into an existing array, instead of allocating a new one.

As the value conversion function you can either use:

  • The C style cast i => (ushort)i which does not complain about integer overflow by default (you can change that in the compiler settings)

    To be really explicit you could write i => unchecked((ushort)i) or i => checked((ushort)i) depending on which behaviour you want.

  • Convert.ToInt16 which throws an OverflowException if the input is larger that short.MaxValue regardless of the compiler settings.

There is a fun/evil trick that allows you to treat a short[] as a ushort[] without actually converting:

short[] signed = new short[]{-1};
signed.GetType().Dump();// short[]

ushort[] unsigned = (ushort[])(object)signed;

unsigned.GetType().Dump();// still short[]
unsigned[0].Dump(); // 65535

It compiles and doesn't throw a runtime error.

The CLR specification says that ushort[] and short[] are compatible, since converting short to ushort preserves the representation. This is a similar mechanism to array covariance.

The C# spec on the other hand does not allow this conversion. That's why the intermediate conversion to object is necessary.