วิธี BitConverter.ToInt16() ใน C# ใช้เพื่อคืนค่าจำนวนเต็มที่ลงนาม 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