Tuesday, June 16, 2026

C# What is BitArray and How it is different from byte Array

BitArray in C# is a collection class that stores bits (0 or 1 values) efficiently instead of storing full bytes or larger data types. It is sealed class implementing a number of interfaces.

public sealed class BitArray : ICollection, IEnumerable, ICloneable

It belongs to the .NET System.Collections namespace and is useful when you need to store many boolean flags while using very little memory.

BitArray offers a clear interface to perform bitwise operations. With it we count and display bits.

Why use BitArray?

Normally storing data in an array occupies 1 byte for each element. So, a boolean array of size 8 will occupy 1 byte for each element, therefore 8 bytes for the array.

bool[] flags = new bool[8];

Here, each bool typically occupies 1 byte in boolean array.

But BitArray stores boolean values as individual bits, so 8 boolean values need only about 8 bits i.e 1 byte internally.

BitArray bits = new BitArray(8);

Creating BitArray

BitArray has many constructors, including ones that receive int32, int32 arrays, byte arrays and default values. When you pass values to the constructor, integers are copied, but bytes and bools are processed first.

public BitArray(bool[] values);
public BitArray(byte[] bytes);
public BitArray(BitArray bits);
public BitArray(int length);
public BitArray(int[] values);
public BitArray(int length, bool defaultValue);

The following example shows different ways to create a BitArray object:
xxxxxxxxxxx

1. Create with size

using System.Collections;

BitArray bits = new BitArray(8);

bits[0] = true;
bits[1] = false;
bits[2] = true;

for (int i = 0; i < bits.Length; i++)
{
    Console.Write(bits[i] ? 1 : 0);
}

Output: 10100000

2. Create from bool array

bool[] data = { true, false, true, true };

BitArray bits = new BitArray(data);

foreach (bool bit in bits)
{
    Console.Write(bit + " ");
}

Output: True False True True

3. Create from byte array

Useful when working with binary data.

byte[] bytes = { 5 }; // 00000101

BitArray bits = new BitArray(bytes);

for (int i = 0; i < 8; i++)
{
    Console.Write(bits[i] ? 1 : 0);
}

Output: 10100000

Explanation:

Decimal number 5 in Binary Representation is 00000101

BitArray reads bits starting from least significant bit first.

Common Properties

Length

BitArray bits = new BitArray(16); 
Console.WriteLine(bits.Length);

Output: 16

Common Methods

You can set all bits of a bit array object using SetAll.

bits.SetAll(true);

Result: 11111111

bitArray.Set(0, false);
bitArray.Set(1, true);
bitArray.Set(2, true);

CopyTo

Copy bits into another array.

BitArray bits = new BitArray(new bool[] { true, false }); 
bool[] arr = new bool[2]; bits.CopyTo(arr, 0);

Logical operations

AND

BitArray a = new BitArray(new bool[] { true, false, true });
BitArray b = new BitArray(new bool[] { true, true, false }); 
a.And(b); foreach(bool x in a)    
Console.Write(x ? 1 : 0);

Output: 100

The BitArray class defines several more useful methods for bitwise operations. The Not(), Or() and Xor() methods provide functionality equivalent to the bitwise operators.

OR

a.Or(b);

Result: 111

XOR

a.Xor(b);

Result: 011

NOT

a.Not();

Not operation flips bits.

101 → 010

Practical usages of BitArray

1. Permission flags

Instead of storing many booleans:

bool canRead;
bool canWrite;
bool canDelete;

Use:

BitArray permissions = new BitArray(3); 
permissions[0] = true; // Read
permissions[1] = false; // Write
permissions[2] = true; // Delete

2. File compression / encoding

Store binary state efficiently.

Example:

101100101010001

3. Feature toggles

Enable/disable application features. Feature values can be stored in BitArray.

Feature 1 → ON
Feature 2 → OFF
Feature 3 → ON

4. Bitmap / image processing

Image uses bits to represent pixels. You can use BitArray for pixel values:

1 → White 0 → Black

5. Algorithms

Used in:

  • Sieve of Eratosthenes (prime numbers)
  • Dynamic programming
  • Graph traversal
  • Bloom filters

BitArray vs Byte Array

Feature

BitArray

byte[]

Stores

Individual bits

Bytes

Memory efficient

Yes

Less

Random access

Yes

Yes

Binary operations

Built in

Manual

Good for flags

Excellent

Average

Flow: C# BitConverter can be used to get byte array and BitArray to access bits.

12345 🠊BitConverter.GetBytes()  ðŸ Š57 48 0 0  ðŸ ŠBitArray  ðŸ ŠIndividual bits accessible

So byte[] stores groups of 8 bits, while BitArray lets you work with each bit separately.

Example using different constructors of BitArray

class Program
{
    static void Main()
    {
        // create bit array using boolean array
        bool[] bools = new bool[] { true, false, true, false };
        var bits = new System.Collections.BitArray(bools);
        foreach (bool bit in bits)
        {
            System.Console.Write(bit + " ");
        }
        Console.WriteLine();
        // create bit array using int array
        int[] ints = new int[] { 1, 2, 3 };
        var bitsInts = new System.Collections.BitArray(ints);
        Console.WriteLine(bitsInts.Count); // 32*3 = 96 bits
        Console.WriteLine(bitsInts.Length); // 32*3 = 96 bits
        foreach (bool bit in bitsInts)
        {
            System.Console.Write(bit + " ");
        }
        Console.WriteLine();
        // defining the size of the bit array
        System.Collections.BitArray bitArray = new System.Collections.BitArray(3);
        bitArray.Set(0, false);
        bitArray.Set(1, true);
        bitArray.Set(2, true);
        foreach (bool bit in bitArray)
        {
            System.Console.Write(bit + " ");
        }
        Console.WriteLine();
        // create bit array using byte array
        byte[] bytes = new byte[] { 10, 29, 45, 55, 200 };
        var bitsBytes = new System.Collections.BitArray(bytes);
        Console.WriteLine(bitsBytes.Count); // 8*5 = 40 bits
    }
}
/*
True False True False
96
96
True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False True True False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False
False True True
40
 */

No comments:

Post a Comment

Hot Topics