Skip to content
February 6, 2011 / pauldundon

.NET BitArray Class Problems

The problem: You are using the .NET BitArray class and get unexpected or bizarre results.

The cause: The BitArray class has some unusual features in its implementation so may not behave as you expect. Specifically:

1. The Equals function compares object identities rather than the contents of the array. That is, Equals will only return true if you compare a BitArray to itself. If you compare two BitArrays with the same contents, Equals will return False.

2. The operator functions (And, Or, Not and Xor) produce a new BitArray containing their result and modify the BitArray on which they are invoked. This is different from the behaviour of, eg, String.Trim which returns a new string but does not modify the host object. This means that two successive calls to, eg, And with the same parameter may produce different results.

Possible solution: Equality can be tested by iterating over the contents of the BitArray, failing at the first bit which differs. If using the And, Or, Not or Xor functions, create a temporary copy of the BitArray using the copy constructor and invoke them on this object.

If you make extensive use of BitArray, consider writing a class which aggregates an instance of BitArray and provides more intuitive implementations of Equals and the four operator functions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: