Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด BitConverter.ToInt16() ใน C# : แปลง 2 ไบต์เป็น Int16

เมธอด BitConverter.ToInt16() ใน C# ใช้แปลง 2 ไบต์ (bytes) ในอาร์เรย์ไบต์ เริ่มจากตำแหน่งที่ระบุ ให้เป็นจำนวนเต็ม 16-bit ที่มีเครื่องหมาย (Int16 / short)

รูปแบบไวยากรณ์ (Syntax)

public static short ToInt16(byte[] value, int startIndex);
  • value : อาร์เรย์ไบต์ต้นทาง
  • startIndex : ตำแหน่งเริ่มต้นในอาร์เรย์ ต้องมีพื้นที่อย่างน้อย 2 ไบต์จากตำแหน่งนี้
  • คืนค่า : Int16 (short) ที่แปลงจาก 2 ไบต์

ตัวอย่างที่ 1: แปลงทุก 2 ไบต์ในอาร์เรย์

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)); // 00-00-07-0A-12-14-19-1A-20
        
        // อ่านทุก 2 ไบต์ เริ่มจาก index 1
        for (int i = 1; i < arr.Length - 1; i = i + 2)
        {
            short res = BitConverter.ToInt16(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + res);
        }
    }
}

ผลลัพธ์

Byte Array = 00-00-07-0A-12-14-19-1A-20
Value at index 1 = 0
Result = 1792
Value at index 3 = 10
Result = 4618
Value at index 5 = 20
Result = 6420
Value at index 7 = 26
Result = 8218

คำอธิบาย (Little-endian):

  • Index 1-2: bytes [0, 7] → 0x0700 = 1792
  • Index 3-4: bytes [10, 18] → 0x120A = 4618
  • Index 5-6: bytes [20, 25] → 0x1914 = 6420
  • Index 7-8: bytes [26, 32] → 0x201A = 8218

ตัวอย่างที่ 2: อาร์เรย์ขนาดเล็ก 3 ไบต์

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 10, 20, 30 };
        
        Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr)); // 0A-14-1E
        
        for (int i = 1; i < arr.Length - 1; i = i + 2)
        {
            short values = BitConverter.ToInt16(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + values);
        }
    }
}

ผลลัพธ์

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

คำอธิบาย: Index 1-2: bytes [20, 30] → 0x1E14 = 7700

สรุปเมธอด BitConverter สำหรับ Integer Types

เมธอด ขนาด (Bytes) ประเภทผลลัพธ์ ช่วงค่า
ToInt16 2 short (Int16) -32,768 ถึง 32,767
ToUInt16 2 ushort (UInt16) 0 ถึง 65,535
ToInt32 4 int (Int32) -2,147,483,648 ถึง 2,147,483,647
ToUInt32 4 uint (UInt32) 0 ถึง 4,294,967,295
ToInt64 8 long (Int64) -9.22×10¹⁸ ถึง 9.22×10¹⁸
ToUInt64 8 ulong (UInt64) 0 ถึง 1.84×10¹⁹

สรุป

  • ใช้ Little-endian (LSB อยู่ index ต่ำ)
  • เหมาะสำหรับ binary protocols, file formats, hardware communication
  • คู่กับ BitConverter.GetBytes(short) สำหรับการแปลงกลับ
  • ต้องเช็ค bounds: startIndex + 2 <= array.Length