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

Lấy hoặc đặt số lượng phần tử trong BitArray C#

Giới thiệu

BitArray có thuộc tính Length (tương đương Count) cho biết số bit. Có thể thay đổi Length để mở rộng hoặc cắt ngắn mảng bit (các bit mới mặc định là false).

Ví dụ 1: So sánh hai BitArray cùng độ dài

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("Elements in BitArray1...");
        foreach (bool res in arr1)
        {
            Console.WriteLine(res);
        }
        
        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
Elements in BitArray1...
False
True
BitArray2 length = 2
Elements in BitArray2...
False
True
Is BitArray1 equal to BitArray2? = False

Ví dụ 2: BitArray với độ dài khác nhau

using System;
using System.Collections;

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

Kết quả

BitArray1 length = 2
Elements in BitArray1...
False
True
BitArray2 length = 1
Elements in BitArray2...
False

Thao tác với Length

BitArray bits = new BitArray(4); // 4 bit: false, false, false, false
bits.Length = 6; // Mở rộng: thêm 2 bit false
bits.Length = 2; // Cắt ngắn: chỉ giữ 2 bit đầu

Lưu ý quan trọng

  • Equals() so sánh tham chiếu, KHÔNG so sánh nội dung bit
  • Để so sánh nội dung: arr1.Cast<bool>().SequenceEqual(arr2.Cast<bool>())
  • Khi giảm Length, dữ liệu bị cắt mất không thể khôi phục
  • Khi tăng Length, bit mới = false