简体   繁体   中英

BitArray and XOR

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

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...

There is no way of doing this with BitArray and for a good reason: the operations like Or or Xor modify the first operand . That's not what | or ^ usually does.

If you wanted, you could create a wrapper that had the operators you want, including copying the value of the first operand before performing the operation.

Unfortunately, since there is no operator overloading in extension classes (the operator overload has to be defined in the class or struct itself), there is no real way of translating those methods into operators. I hope (as I'm sure many others do as well) that this will be changed in the future, but for now there's no way of doing that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM