Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsBuffer() for sbyte[]?

Tags:

c#

.net

byte

uwp

I'm working on a small task that requires me to create IBuffer instances from byte arrays.

With regular byte arrays, the .AsByte() extension method from System.Runtime.InteropServices.WindowsRuntime works just fine, however many of my arrays are actually sbyte[] (code is ported legacy Java code, where some of the values are defined as e.g. new sbyte[] { -86, 27, 28, 29, -1 };

Is there an extension method that covers the sbyte[] use case too? Unfortunately not much information is available about sbyte array operations (and conversion into byte arrays).

like image 962
fonix232 Avatar asked Feb 12 '26 02:02

fonix232


2 Answers

You can try this conversion method before AsBuffer()

var signedBytes = new sbyte[] { -86, 27, 28, 29, -1 };
IBuffer buffer = Array.ConvertAll(signedBytes, b => (byte)b).AsBuffer();

Array.ConvertAll Documentation

This method was introduced in .NET 2.0 and exists in all version after that.

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

EDIT:

After further chatting it seems that this code lives in a Class Library (Portable) not a regular Class Library so ConvertAll is not available.

Can achieve the above with this version.

var signedBytes = new sbyte[] { -86, 27, 28, 29, -1 };
IBuffer buffer = signedBytes.Cast<byte>().ToArray().AsBuffer();
like image 77
Cubicle.Jockey Avatar answered Feb 13 '26 17:02

Cubicle.Jockey


Just convert sbyte[] to byte[] and after that use the other method. Here an example.

sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = (byte[]) (Array)signed; 
like image 39
mybirthname Avatar answered Feb 13 '26 15:02

mybirthname