Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức BitConverter.ToInt16 () trong C #


Phương thức BitConverter.ToInt16 () trong C # được sử dụng để trả về số nguyên có dấu 16 bit được chuyển đổi từ hai byte tại một vị trí được chỉ định trong mảng byte.

Cú pháp

Cú pháp như sau -

public static short ToInt16 (byte[] val, int begnIndex);

Ở trên, val là mảng byte, trong khi đó, seeknIndex là vị trí bắt đầu trong val.

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ -

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

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ khác -

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

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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