-1

I recently bought some Bluetooth LE Devices and wanted to read the Data coming from them in Unity. The Problem is I used a library that gives me only a byte array. But I need a sbyte Array.

Example output:
83,186,1,3
But I want:
38, -70,1,3

Here is my Code:

int x = 0;
int y = 0;
z = 0;

result = Convert.ToString(bytes[3], 2).PadLeft(8, '0');
Debug.Log("First Conversion:" + result.Remove(0,1) + " Original:" + bytes[3]);
sbyte result1 = sbyte.Parse(result.Remove(0,1));
Debug.Log("Conversion:" + result1 + " Original:" + bytes[3]);

I've tried this for the last 5h. The farthest I've got was an error that said that my number was too small or too large.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    What is `bytes`? Why are you converting data to a string and then parsing? Please provide a [mcve]. – Jon Skeet Jan 23 '23 at 16:51
  • Assuming that `bytes` is an array of bytes that you want to convert to `sbyte`, you can do `unchecked { sbyte[] sbytes = bytes.Select(b => (sbyte)b).ToArray(); }` – Matthew Watson Jan 23 '23 at 16:55
  • 2
    why does your snippet contain unused variables x,y and z? please only provide relevant stuff if you're asking for help. how does 83 become 38 by converting it to sbyte? I guess this is a typo... your title asks how to convert int to sbyte while your post asks how to convert a byte array to a sbyte array. come on! – Piglet Jan 23 '23 at 17:03

1 Answers1

2

There is an easy method of conversion, you can use:

sbyte[] signed = (sbyte[]) (Array) unsigned;

It works due to byte and sbyte having the same length in memory. They can be converted without the need to change memory representation.


However,

the method above might lead to bugs and weird behaviour with the debugger. If the byte array is not that big, you could use Array.ConvertAll instead.

sbyte[] signed = Array.ConvertAll(unsigned, b => unchecked((sbyte)b));
SimpleCoder
  • 474
  • 4
  • 18