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

ตัวอย่าง Buffer.GetByte ใน C#


ภาพรวม

เมธอด Buffer.GetByte() ใช้ อ่านค่าไบต์ ที่ตำแหน่งที่ระบุในอาร์เรย์

รูปแบบการใช้งาน

int[] arr = { 3, 4, 12 };
for (int i = 0; i < Buffer.ByteLength(arr); i++)
    Console.WriteLine(Buffer.GetByte(arr, i));

ตัวอย่างโค้ดเต็ม

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));
    }
}

ผลลัพธ์

3
0
0
0
4
0
0
0
12
0
0
0

คำอธิบาย

  • Buffer.ByteLength(arr) คืนขนาดรวมเป็นไบต์ (3 ints × 4 ไบต์ = 12 ไบต์)
  • แต่ละ int (32-bit) จัดเก็บแบบ little-endian: ค่าต่ำกว่า 256 จะอยู่ที่ไบต์แรก ไบต์ที่เหลือเป็น 0
  • ใช้สำหรับ: low-level byte manipulation, serialization, interop กับ unmanaged code