เมธอด BitConverter.ToInt32() ใน C# ใช้แปลง 4 ไบต์ (bytes) ในอาร์เรย์ไบต์ เริ่มจากตำแหน่งที่ระบุ ให้เป็นจำนวนเต็ม 32-bit ที่มีเครื่องหมาย (Int32)
รูปแบบไวยากรณ์ (Syntax)
public static int ToInt32(byte[] value, int startIndex);
value: อาร์เรย์ไบต์ต้นทางstartIndex: ตำแหน่งเริ่มต้นในอาร์เรย์ (0-based) ต้องมีพื้นที่อย่างน้อย 4 ไบต์จากตำแหน่งนี้- คืนค่า : Int32 ที่แปลงจาก 4 ไบต์
ตัวอย่างที่ 1: แปลงจากตำแหน่งต่างๆ ในอาร์เรย์
using System;
public class Demo
{
public static void Main()
{
byte[] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr)); // 0A-14-1E-28-32
// เริ่มจาก index 1 (ค่า 20) อ่าน 4 ไบต์: 20, 30, 40, 50
for (int i = 1; i < arr.Length - 3; i = i + 4)
{
int res = BitConverter.ToInt32(arr, i);
Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
Console.WriteLine("Result = " + res);
}
}
}
ผลลัพธ์
Byte Array = 0A-14-1E-28-32 Value at index 1 = 20 Result = 841489940
คำอธิบาย: ไบต์ 4 ตัวคือ 20(0x14), 30(0x1E), 40(0x28), 50(0x32) → 0x32281E14 = 841,489,940 (Little-endian)
ตัวอย่างที่ 2: อาร์เรย์ยาวกว่า หลายกลุ่ม 4 ไบต์
using System;
public class Demo
{
public static void Main()
{
byte[] arr = { 0, 0, 10, 15, 20, 26, 32, 34, 40 };
Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr)); // 00-00-0A-0F-14-1A-20-22-28
for (int i = 1; i < arr.Length - 3; i = i + 4)
{
int res = BitConverter.ToInt32(arr, i);
Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
Console.WriteLine("Result = " + res);
}
}
}
ผลลัพธ์
Byte Array = 00-00-0A-0F-14-1A-20-22-28 Value at index 1 = 0 Result = 336529920 Value at index 5 = 26 Result = 673325082
ข้อสังเกตสำคัญ: Endianness
BitConverterใช้ Little-endian (ค่าเริ่มต้นของ x86/x64) หมายถึง byte ที่มีน้ำหนักน้อยสุด (LSB) อยู่ที่ index ต่ำสุดBitConverter.IsLittleEndianบอก endianness ของระบบ (ปกติเป็น true)- หากอ่านข้อมูลจาก network (Big-endian) หรือไฟล์บางรูปแบบ ต้องกลับลำดับไบต์ก่อนแปลง
เมธอดเกี่ยวข้องใน BitConverter
| เมธอด | คำอธิบาย |
|---|---|
ToInt16(byte[], int) |
แปลง 2 ไบต์ → Int16 (short) |
ToInt32(byte[], int) |
แปลง 4 ไบต์ → Int32 (int) |
ToInt64(byte[], int) |
แปลง 8 ไบต์ → Int64 (long) |
ToDouble(byte[], int) |
แปลง 8 ไบต์ → Double |
ToSingle(byte[], int) |
แปลง 4 ไบต์ → Single (float) |
GetBytes(value) |
แปลงค่าตัวเลข → byte[] (ย้อนกลับ) |
สรุป
- ใช้สำหรับแปลง binary data (network packets, file formats, serialization)
- ต้องตรวจสอบ bounds:
startIndex + 4 <= array.Length - คำนึงถึง Endianness เมื่อแลกเปลี่ยนข้อมูลข้ามแพลตฟอร์ม