Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

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 it nicely and quickly, without copying all the data or using unsafe magic?

like image 935
Vilx- Avatar asked May 06 '09 14:05

Vilx-


People also ask

How to Convert SByte to byte in c#?

If you are using . NET 3.5+, you can use the following: byte[] dest = Array. ConvertAll(sbyteArray, (a) => (byte)a);

What is a byte [] in C#?

In C#, byte is the data type for 8-bit unsigned integers, so a byte[] should be an array of integers who are between 0 and 255, just like an char[] is an array of characters.

What is the difference between byte and SByte?

byte is used to work with unsigned byte data, it works with an only positive value between in the range of 0 to 255. sbyte is used to work with the signed byte data, it works with both types of data (Negative and Positive), it can store the between in the range of -128 to 127.


3 Answers

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; 
like image 71
Gus Avatar answered Sep 18 '22 22:09

Gus


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
like image 28
Marc Gravell Avatar answered Sep 20 '22 22:09

Marc Gravell


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.

like image 6
Clinton Avatar answered Sep 21 '22 22:09

Clinton