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

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


ภาพรวม

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

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

int[] arr = { 3, 4, 12 }; // แต่ละ int = 4 ไบต์
Buffer.SetByte(arr, 3, 20); // ตั้งค่าไบต์ที่ offset 3 เป็น 20

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

using System;

public class Demo
{
    public static void Main()
    {
        int[] arr = { 3, 4, 12 };
        Console.WriteLine("Initial Array...");
        for (int i = 0; i < Buffer.ByteLength(arr); i++)
            Console.WriteLine(Buffer.GetByte(arr, i));
        Buffer.SetByte(arr, 3, 20);
        Console.WriteLine("New Array...");
        for (int i = 0; i < Buffer.ByteLength(arr); i++)
            Console.WriteLine(Buffer.GetByte(arr, i));
    }
}

ผลลัพธ์

Initial Array...
3
0
0
0
4
0
0
0
12
0
0
0
New Array...
3
0
0
20
4
0
0
0
12
0
0
0

คำอธิบาย

  • int[] แต่ละตัว = 4 ไบต์ (little-endian): 3 = [3,0,0,0], 4 = [4,0,0,0], 12 = [12,0,0,0]
  • Buffer.SetByte(arr, 3, 20) ตั้งค่าไบต์ที่ 4 (index 3) เป็น 20 → เปลี่ยนไบต์ที่ 2 ของ int แรก (ซึ่งเป็น 0) กลายเป็น 20
  • ผลลัพธ์ int แรกกลายเป็นค่าที่แปลก (3 + 20*256 = 5123) แต่ตัวอย่างแสดงแค่ระดับไบต์
  • ควรระวัง: การเขียนทับไบต์กลางของ multi-byte types จะทำให้ค่าผิดปกติ