Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitArray and XOR

Tags:

c#

.net

I'm looking for an operator based way of working with bit masks and bitwise boolean operations (XOR / NOR / OR / AND / NOT / EQV / etc). Generally I really like an extension method style approach, but in this case, I find it a little messy.

Is there a terser way of working with bits in C#?

        BitArray a = new BitArray(0x001);
        BitArray b = new BitArray(0x100);
        BitArray c = new BitArray(0x010);

        BitArray test = a | b;   // won't compile
        BitArray test2 = a ^ c;  // won't compile

        BitArray test3 = a.Or(b);   // compiles
        BitArray test4 = a.Xor(c);  // compiles
like image 990
sgtz Avatar asked Feb 07 '12 06:02

sgtz


People also ask

What is BitArray in C#?

The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). It is used when you need to store the bits but do not know the number of bits in advance.

What is XOR C#?

Logical exclusive OR operator ^ The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false , or x evaluates to false and y evaluates to true .

How do you Bitwise XOR in an array in Python?

Practical Data Science using Python We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums. So, if the input is like n = 6, start = 2, then the output will be 14 because the array will be like [2+2*0, 2+2*1, ...


1 Answers

There's no way of doing it directly with BitArray - but you could always create a wrapper class which contained a BitArray, and define your own operators there.

Of course, if you're dealing with 64 bits or fewer, you could just use a long or ulong and be done with it...

like image 180
Jon Skeet Avatar answered Sep 30 '22 14:09

Jon Skeet