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

เมธอด Random.NextBytes() ใน C# : เติมอาร์เรย์ไบต์ด้วยค่าสุ่ม

เมธอด Random.NextBytes() ใน C# ใช้เติมข้อมูลในอาร์เรย์ไบต์ (byte[]) ด้วยตัวเลขสุ่ม (ค่า 0-255) เหมาะสำหรับการสร้างข้อมูลสุ่มแบบทึบ (random data), salt, nonce, หรือ test data

รูปแบบไวยากรณ์ (Syntax)

public virtual void NextBytes(byte[] buffer);
  • buffer : อาร์เรย์ไบต์ที่จะถูกเติมค่าสุ่ม (จะถูกแก้ไขโดยตรง)

ตัวอย่างที่ 1: ใช้ร่วมกับ Next() และ Next(int)

using System;

public class Demo
{
    public static void Main()
    {
        Random r = new Random();
        Random r2 = new Random();
        Random r3 = new Random();
        
        Byte[] arr = new Byte[5];
        r3.NextBytes(arr); // เติมค่าสุ่มใน arr
        
        Console.WriteLine("Random numbers (Next())......");
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(r.Next());
        }
        
        Console.WriteLine("\nRandom numbers from 0 to 9 (Next(10))......");
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(r2.Next(10));
        }
        
        Console.WriteLine("\nRandom numbers in the byte array (NextBytes).....");
        for (int i = 0; i < arr.GetUpperBound(0); i++)
        {
            Console.WriteLine(arr[i]);
        }
    }
}

ผลลัพธ์ (ตัวอย่าง)

Random numbers.....
2081486546
329484380
1639318640
1499756340
2122408387

Random numbers from 0 to 9.....
9
1
7
6
9

Random numbers in the byte array...
210
92
112
52

ตัวอย่างที่ 2: อาร์เรย์ขนาดเล็ก

using System;

public class Demo
{
    public static void Main()
    {
        Random r = new Random();
        Byte[] arr = new Byte[2];
        r.NextBytes(arr);
        
        Console.WriteLine("Random numbers in the byte array.....");
        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }
}

ผลลัพธ์ (ตัวอย่าง)

Random numbers in the byte array...
173
11

สรุปและข้อสังเกต

  • แต่ละ element ใน byte[] จะได้ค่าสุ่ม 0-255 (ค่าทั้งช่วงของ byte)
  • เมธอดนี้เปลี่ยนค่า array โดยตรง (pass by reference) ไม่คืนค่า array ใหม่
  • เหมาะสำหรับ: สร้าง cryptographic salt, random file data, test binary data
  • สำหรับความปลอดภัยทางเข้ารหัส ควรใช้ RandomNumberGenerator.GetBytes() แทน
  • ไม่มี overload สำหรับกำหนดช่วงค่า (จะได้ค่าเต็มช่วง byte เสมอ)