简体   繁体   中英

Convert int to sbyte in C#

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM