如何在 C# 中将 sbyte[] 转换为 byte[]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/829983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a sbyte[] to byte[] in C#?
提问by Vilx-
I've got a function which fills an array of type sbyte[], and I need to pass this array to another function which accepts a parameter of type byte[].
我有一个函数来填充 sbyte[] 类型的数组,我需要将此数组传递给另一个接受 byte[] 类型参数的函数。
Can I convert it nicely and quickly, without copying all the data or using unsafe
magic?
我能否在不复制所有数据或使用unsafe
魔法的情况下快速快速地转换它?
采纳答案by Gus
Yes, you can.
Since both byte
and sbyte
have the same binary representation there's no need to copy the data.
Just do a cast to Array, then cast it to byte[]
and it'll be enough.
是的你可以。由于两个byte
与sbyte
具有相同的二进制表示没有必要复制数据。只需对 Array 进行强制转换,然后将其强制转换为byte[]
,就足够了。
sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = (byte[]) (Array)signed;
回答by Marc Gravell
You will have to copy the data (only reference-type arrays are covariant) - but we can try to do it efficiently; Buffer.BlockCopy
seems to work:
您将不得不复制数据(只有引用类型的数组是协变的)——但我们可以尝试高效地进行;Buffer.BlockCopy
似乎工作:
sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
If it was a reference-type, you can just cast the reference without duplicating the array:
如果它是引用类型,您可以只转换引用而不复制数组:
Foo[] arr = { new Foo(), new Foo() };
IFoo[] iarr = (IFoo[])arr;
Console.WriteLine(ReferenceEquals(arr, iarr)); // true
回答by Clinton
If you are using .NET 3.5+, you can use the following:
如果您使用的是 .NET 3.5+,则可以使用以下内容:
byte[] dest = Array.ConvertAll(sbyteArray, (a) => (byte)a);
Which is, I guess effectively copying all the data.
也就是说,我想有效地复制所有数据。
Note this function is also in .NET 2.0, but you'd have to use an anonymous method instead.
请注意,此函数也在 .NET 2.0 中,但您必须改用匿名方法。