C# 中的 BitConverter.ToInt16() 方法

csharpserver side programmingprogramming更新于 2025/9/15 11:07:00

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("
Value = "+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("
Value = "+arr[i]);          Console.WriteLine("Result = "+values);       }    } }

输出

这将产生以下输出 −

Byte Array = 0A-14-1E
Value = 20
Result = 7700

相关文章