Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy giá trị bit tại vị trí cụ thể trong BitArray C#

Giới thiệu

BitArray (namespace System.Collections) quản lý mảng các bit dưới dạng Boolean. Phương thức Get(int index) hoặc indexer [index] trả về giá trị bit tại vị trí chỉ định.

Ví dụ 1: So sánh hai BitArray

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        BitArray arr1 = new BitArray(2);
        BitArray arr2 = new BitArray(2);
        
        arr1[0] = false;
        arr1[1] = true;
        
        Console.WriteLine("BitArray1 length = " + arr1.Length);
        Console.WriteLine("BitArray1 first element = " + arr1.Get(0));
        
        arr2[0] = false;
        arr2[1] = true;
        
        Console.WriteLine("\nBitArray2 length = " + arr2.Length);
        Console.WriteLine("Elements in BitArray2...");
        foreach (bool res in arr2)
        {
            Console.WriteLine(res);
        }
        
        Console.WriteLine("\nIs BitArray1 equal to BitArray2? = " + arr2.Equals(arr1));
    }
}

Kết quả

BitArray1 length = 2
BitArray1 first element = False
BitArray2 length = 2
Elements in BitArray2...
False
True
Is BitArray1 equal to BitArray2? = False

Ví dụ 2: Lấy nhiều bit tại các vị trí khác nhau

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        BitArray arr = new BitArray(5);
        arr[0] = false;
        arr[1] = true;
        arr[2] = false;
        arr[3] = true;
        
        Console.WriteLine("BitArray length = " + arr.Length);
        Console.WriteLine("BitArray first element = " + arr.Get(0));
        Console.WriteLine("BitArray second element = " + arr.Get(1));
    }
}

Kết quả

BitArray length = 5
BitArray first element = False
BitArray second element = True

Lưu ý quan trọng

  • Equals() so sánh tham chiếu (reference equality), không so sánh nội dung bit
  • Để so sánh nội dung, duyệt qua từng phần tử hoặc dùng Cast<bool>().SequenceEqual()
  • Indexer [index] cho phép cả get và set
  • Get(index) chỉ đọc, an toàn hơn
  • Chỉ mục hợp lệ: 0 đến Length-1

Phương thức liên quan

  • Set(int index, bool value) - Đặt giá trị bit
  • SetAll(bool value) - Đặt tất cả bit
  • Get(int index) - Lấy giá trị bit