Gets or sets the value of the bit at a specific position in the BitArray in C#

CsharpServer Side ProgrammingProgramming

To get or set the value of the bit at a specific position in the BitArray, the code is as follows −

Example

 Live Demo

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));
   }
}

Output

This will produce the following output −

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

Example

Let us now see another example −

 Live Demo

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));
      arr1[0] = true;
      Console.WriteLine("BitArray1 first element [UPDATED] = "+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));
   }
}

Output

This will produce the following output −

BitArray1 length = 2
BitArray1 first element = False BitArray1 first element [UPDATED] = True BitArray2 length = 2
Elements in BitArray2...
False
True
Is BitArray1 equal to BitArray2? = False
raja
Published on 06-Dec-2019 07:30:21
Advertisements