I need something a little more than the System.Collections.BitArray
class in my application. Specifically, I need the bit array:
- To be immutable
- To implement equality using value semantics
I created my own struct
, largely copying the internals of the BitArray
implementation. (Thanks, .Net Reflector!)
I don't deal everyday with bitwise operations, so I don't have the highest degree of confidence in my equality implementation. (It's passing the unit tests I am throwing at it, but I may be missing edge cases.) I have my proposed solutions as answers below. I would appreciate others' feedback and answers for something that may be more correct or efficient.
Just like the CLR BitArray
, the length
field refers to the number of bits in the struct and the array
field (or Array
property) refers to the 32-bit integer array that represents the bits.
[CLARIFICATION] I have chosen to take the easy route in my constructors and other methods so that I cannot rely on the unnecessary bits being zeros. For example,
Not()
is implemented by bitwise negation (~
) on the integer array elements.- A constructor is available that takes a length and boolean to initialize all bits. If the initialization value is true, I set all elements of the int array to -1 (in two's complement, represented by all 1's)
- Etc.
Thus, I need to handle (or, rather, ignore) them in the comparison. A fine solution would also be to keep those bits zeroed at all times, but in my situation that will result in more work (both for the computer and me!)