简体   繁体   English

将C#中的int转sbyte

[英]Convert int to sbyte in C#

I recently bought some Bluetooth LE Devices and wanted to read the Data coming from them in Unity.我最近买了一些蓝牙 LE 设备,想在 Unity 中读取来自它们的数据。 The Problem is I used a library that gives me only a byte array.问题是我使用了一个只给我一个字节数组的库。 But I need a sbyte Array.但我需要一个 sbyte 数组。

Example output:示例 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.在过去的 5 小时里,我已经尝试过了。 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.它的工作原理是 byte 和 sbyte 在 memory 中具有相同的长度。无需更改 memory 表示即可转换它们。


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.如果字节数组不是那么大,您可以改用Array.ConvertAll

sbyte[] signed = Array.ConvertAll(unsigned, b => unchecked((sbyte)b));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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