Phương thức BitConverter.ToInt16() trong C# được dùng để chuyển đổi 2 byte từ một mảng byte tại vị trí chỉ định thành một số nguyên 16-bit có dấu (short).
Cú pháp
public static short ToInt16(byte[] value, int startIndex);
value: Mảng byte nguồn.startIndex: Vị trí bắt đầu (phải có ít nhất 2 byte từ vị trí này).
Trả về: Số short (Int16) được hình thành từ 2 byte (theo endianness hệ thống).
Ví dụ 1: Mảng byte 9 phần tử, đọc nhiều cặp
using System;
public class Demo
{
public static void Main()
{
byte[] arr = { 0, 0, 7, 10, 18, 20, 25, 26, 32 };
Console.WriteLine("Mảng byte = {0}", BitConverter.ToString(arr)); // 00-00-07-0A-12-14-19-1A-20
// Đọc từng cặp 2 byte, bắt đầu từ chỉ mục 1, bước 2
for (int i = 1; i < arr.Length - 1; i = i + 2)
{
short res = BitConverter.ToInt16(arr, i);
Console.WriteLine("\nGiá trị byte tại [" + i + "] = " + arr[i]);
Console.WriteLine("Kết quả ToInt16 = " + res);
}
}
}
Kết quả (Little-Endian)
Mảng byte = 00-00-07-0A-12-14-19-1A-20 Giá trị byte tại [1] = 0 Kết quả ToInt16 = 1792 Giá trị byte tại [3] = 10 Kết quả ToInt16 = 4618 Giá trị byte tại [5] = 20 Kết quả ToInt16 = 6420 Giá trị byte tại [7] = 26 Kết quả ToInt16 = 8218
Giải thích (Little-Endian)
- Tại [1]: byte {0, 7} → 0x0700 = 1792
- Tại [3]: byte {10, 18} → 0x120A = 4618
- Tại [5]: byte {20, 25} → 0x1914 = 6420
- Tại [7]: byte {26, 32} → 0x201A = 8218
Ví dụ 2: Mảng byte 3 phần tử
using System;
public class Demo
{
public static void Main()
{
byte[] arr = { 10, 20, 30 };
Console.WriteLine("Mảng byte = {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("\nGiá trị byte tại [" + i + "] = " + arr[i]);
Console.WriteLine("Kết quả ToInt16 = " + values);
}
}
}
Kết quả
Mảng byte = 0A-14-1E Giá trị byte tại [1] = 20 Kết quả ToInt16 = 7700
Giải thích
Tại [1]: byte {20, 30} → 0x1E14 = 7700 (decimal).
Các phương thức liên quan (2 byte)
| Phương thức | Kiểu trả về | Phạm vi |
|---|---|---|
ToInt16 |
short | -32,768 đến 32,767 |
ToUInt16 |
ushort | 0 đến 65,535 |
ToChar |
char | U+0000 đến U+FFFF |
Đối ngược: GetBytes(short)
short s = 30000; byte[] bytes = BitConverter.GetBytes(s); // Little-endian: bytes[0] = 0x30, bytes[1] = 0x75 (0x7530 = 30000) short s2 = BitConverter.ToInt16(bytes, 0); // s2 == 30000
Lưu ý
- Phụ thuộc
BitConverter.IsLittleEndian. - Ném
ArgumentNullException(mảng null) hoặcArgumentOutOfRangeException(index sai). - Dùng
BinaryPrimitives.ReadInt16LittleEndian/BigEndian(.NET Core 2.1+) để an toàn cross-platform. - Ứng dụng: đọc file binary, header network packet, sensor data, interop.