[英]convert short[] to ushort[]
I need to convert short[] to ushort[] in C# 我需要在C#中将short []转换为ushort []
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 谢谢
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. 两者都利用LINQ将转换功能应用于集合的能力。
As normal solution I recommend: 作为常规解决方案,我建议:
unsigned = ConvertAll(signed, i => (ushort)i)
This produces less garbage than LINQ solutions while being similarly concise and readable. 与LINQ解决方案相比,这产生的垃圾更少,并且同样简洁明了。
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) C样式强制转换i => (ushort)i
,默认情况下它不会抱怨整数溢出(您可以在编译器设置中进行更改)
To be really explicit you could write i => unchecked((ushort)i)
or i => checked((ushort)i)
depending on which behaviour you want. 确切地说,您可以根据所需的行为编写i => unchecked((ushort)i)
或i => checked((ushort)i)
。
Convert.ToInt16
which throws an OverflowException
if the input is larger that short.MaxValue
regardless of the compiler settings. 不管编译器设置如何,如果输入大于short.MaxValue
,则Convert.ToInt16
会引发OverflowException
。 There is a fun/evil trick that allows you to treat a short[]
as a ushort[]
without actually converting: 有一个有趣的/恶作剧的技巧,可让您将short[]
视为ushort[]
而无需实际转换:
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. CLR规范说ushort[]
和short[]
是兼容的,因为将short
转换为ushort
保留表示形式。 This is a similar mechanism to array covariance. 这是与数组协方差相似的机制。
The C# spec on the other hand does not allow this conversion. 另一方面,C#规范不允许这种转换。 That's why the intermediate conversion to object
is necessary. 这就是为什么必须将object
中间转换的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.