How to convert a sbyte[] to byte[] in C#?

前端 未结 3 1362
情话喂你
情话喂你 2020-12-08 19:22

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[].

Can I convert

相关标签:
3条回答
  • 2020-12-08 20:09

    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:

        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
    
    0 讨论(0)
  • 2020-12-08 20:13

    If you are using .NET 3.5+, you can use the following:

    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.

    0 讨论(0)
  • 2020-12-08 20:15

    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.

    sbyte[] signed = { -2, -1, 0, 1, 2 };
    byte[] unsigned = (byte[]) (Array)signed; 
    
    0 讨论(0)
提交回复
热议问题