C#中反轉BitArray中所有位值


BitArray是表示為一系列1和0的布林值集合。它通常用於有效地儲存和操作二進位制資料。在C#中,BitArray類是System.Collections名稱空間的一部分,它允許您使用位運算子運算元組中的各個位。

反轉BitArray中的所有位值

要在C#中反轉BitArray中的所有位值,您可以使用異或運算子(^)和數字1。如果比較的位不同,此運算子返回1;如果相同,則返回0。透過將此運算子應用於BitArray中的每個位,您可以反轉所有位值。

示例1

以下示例演示如何在C#中反轉BitArray中的所有位值。

演算法

  • 步驟1 - 建立一個新的BitArray來儲存反轉的值。

  • 步驟2 - 迴圈遍歷原始BitArray中的每個位。

  • 步驟3 - 使用按位非運算子(~)反轉每個位的值。

  • 步驟4 - 將反轉後的值儲存在新BitArray中。

  • 步驟5 - 返回新的BitArray。

using System;
using System.Collections;
class Program{
   static void Main(string[] args){
      // Create a new BitArray with some initial values
      BitArray bits = new BitArray(new[] { true, false, true, false });

      // Invert all the bit values using XOR with 1
      for (int i = 0; i < bits.Length; i++){
         bits[i] ^= true;
      }

      // Print the inverted bit values
      for (int i = 0; i < bits.Length; i++){
         Console.Write(bits[i] ? "1" : "0");
      }
      Console.ReadLine();
   }
}

輸出

執行上面的程式碼時輸出。此輸出對應於原始BitArray(1010)的反轉位值。

0101

示例2

以下示例演示如何在C#中反轉BitArray中的所有位值。

演算法

  • 步驟1 - 使用所需大小建立一個BitArray物件。

  • 步驟2 - 迴圈遍歷BitArray中的每個索引。

  • 步驟3 - 使用BitArray.Set方法,並使用當前索引的否定值作為引數,反轉當前索引處的值。

using System;
using System.Collections;
class Program {
   static void Main(string[] args) {
      int size = 8;
      BitArray bits = new BitArray(size);
      for (int i = 0; i < size; i++) {
         bits[i] = (i % 2 == 0);
      }
      Console.WriteLine("Before inversion:");
      PrintBits(bits);
      InvertBits(bits);
      Console.WriteLine("After inversion:");
      PrintBits(bits);
   }
   static void InvertBits(BitArray bits) {
      for (int i = 0; i < bits.Count; i++) {
         bits.Set(i, !bits[i]);
      }
   }
   static void PrintBits(BitArray bits) {
      for (int i = 0; i < bits.Count; i++) {
         Console.Write(bits[i] ? "1" : "0");
      }
      Console.WriteLine();
   }
}

輸出

Before inversion:
01010101
After inversion:
10101010

結論

在C#中反轉BitArray中的所有位值是一項簡單的任務,可以使用與值1的異或運算子來完成。此技術在處理二進位制資料時非常有用,可以幫助您有效地運算元組中的各個位。

更新於:2023年4月25日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.