ajaxi
ajaxi

Reputation: 5

On understanding bitwise in c# Arrays

I spent long time understanding how programmers use the advantage of speedy binary representation of data in C# arrays but I just dont get it.

for example If I have 2 arrays A, and B to store 0/1 data. In normal situation we do like this :

    bool flag=true;
    int[] A = new int[10] { 1, 0, 0, 0, 1, 1, 0, 1, 0, 0 };
    int[] B = new int[10] { 1, 1, 1, 0, 0, 1, 0, 1, 0, 0 };
    // For comparing the first 5 bits :
    for(int i=0;i<5;i++)
        if (A[i] != B[i])
        {
            flag = false;
            break;
        } 
    // Accessing the i*th* positions is :
    A[7]=1;
   int x=B[5];

What if I need to repeat this code for thousands of times ? or even the arrays are very large ? the straight answer will be to represent the data as bit packed arrays and apply things like bitwise operations or bitmasking ... etc.

My question is how to switch to the binary world in c# ? for more accurate question, How to rewrite the code above in very efficient way using the binary representation and bit wise operations ? Answer with demo code will be much appreciated.

[UPDATE] I am looking for an answer that utilizes storing binary data as bytes or bits and uses shifting bits for accessing/comparing the arrays

Upvotes: 0

Views: 325

Answers (1)

jdphenix
jdphenix

Reputation: 15425

Well, a direct translation using BitVector32 -

var flag = true;
var A = new BitVector32(0x234);
var B = new BitVector32(0x394);

for (var i = 0; i < 5; i++)
{
    if (A[i] != B[i])
    {
        flag = false;
        break;
    }
}

A[7] = true;
bool x = B[5];

You can also use a BitArray if you need mutable size for the array. One important note on BitArray is that it is slower - but the optimizations (a packed int or int[]) are similar.


You also have language supported flags enums available - it may fit your use case. Or maybe not. But they are there.

[Flags]
enum MyFlags
{
    Foo = 0x0001,
    Bar = 0x0002, 
    Baz = 0x0004, 
    All = Foo | Bar | Baz
}

class Program
{
    static void Main(string[] args)
    {
        MyFlags flags = MyFlags.Foo | MyFlags.Baz;
        MyFlags isBar = MyFlags.Bar & flags;

        Console.WriteLine(isBar);
    }
}

Upvotes: 0

Related Questions