C#中的BitConverter.ToInt16()方法用于返回从字节数组中指定位置的两个字节转换而来的16位带符号整数。
语法如下-
public static short ToInt16 (byte[] val, int begnIndex);
在上面,val是字节数组,而begnIndex是val中的开始位置。
现在让我们看一个例子-
using System; public class Demo { public static void Main(){ byte[] arr = { 0, 0, 7, 10, 18, 20, 25, 26, 32}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 1; i < arr.Length - 1; i = i + 2) { short res = BitConverter.ToInt16(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } }
输出结果
这将产生以下输出-
Byte Array = 00-00-07-0A-12-14-19-1A-20 Value = 0 Result = 1792 Value = 10 Result = 4618 Value = 20 Result = 6420 Value = 26 Result = 8218
现在让我们来看另一个示例-
using System; public class Demo { public static void Main(){ byte[] arr = { 10, 20, 30}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 1; i < arr.Length - 1; i = i + 2) { short values = BitConverter.ToInt16(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+values); } } }
输出结果
这将产生以下输出-
Byte Array = 0A-14-1E Value = 20 Result = 7700