Giới thiệu
Buffer.GetByte(Array array, int index) đọc giá trị byte tại vị trí byte index trong mảng. Dùng để kiểm tra biểu diễn byte level của dữ liệu.
Ví dụ cơ bản
int[] arr = { 3, 4, 12 };
for (int i = 0; i < Buffer.ByteLength(arr); i++)
Console.WriteLine(Buffer.GetByte(arr, i));
Ví dụ hoàn chỉnh
using System;
public class Demo
{
public static void Main()
{
int[] arr = { 3, 4, 12 };
for (int i = 0; i < Buffer.ByteLength(arr); i++)
Console.WriteLine(Buffer.GetByte(arr, i));
}
}
Kết quả
3 0 0 0 4 0 0 0 12 0 0 0
Giải thích (Little-Endian)
int= 4 byte, little-endian (byte thấp địa chỉ thấp).- 3 = 0x00000003 -> bytes: [3, 0, 0, 0]
- 4 = 0x00000004 -> bytes: [4, 0, 0, 0]
- 12 = 0x0000000C -> bytes: [12, 0, 0, 0]
Ứng dụng thực tế
- Debug/inspect biểu diễn bộ nhớ.
- Serialization tùy chỉnh (custom binary format).
- Interop với native code (C/C++).
- Xử lý file binary, network packet.
Lưu ý
- Chỉ dùng với mảng kiểu primitive (bool, byte, char, short, int, long, float, double).
- Index là byte offset (0 đến ByteLength-1).
- Trên big-endian architecture, thứ tự byte ngược lại.
- Dùng
BitConvertercho chuyển đổi an toàn hơn:BitConverter.GetBytes(3)-> [3,0,0,0].