Posted By

pckujawa on 01/12/10


Tagged

binary


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

khouser
danfinrud55


Tips for dealing with binary arrays (BitArray, BitVector32, etc) in .NET


 / Published in: C#
 

I just want to jot this down: When you are working with binary data in C#, you often need to deal with individual bits. From my experience and searching, .NET doesn't have a good way to deal with bits. However, you can use the System.Collections.BitArray and System.Collections.Specialized.BitVector32 to mostly do what you need without much hassle.

The BitArray is good for variable-size collections. It uses booleans internally (you may think that this wastes space, and it does, but it optimizes performance for a modern PC) and create a byte array from its internal bits (using CopyTo). E.g. if you have a 57-bit BitArray, you can CopyTo an 8-byte (64-bit) array and then transmit that data, if necessary.

BitVector32 has been most useful for me in displaying binary values (e.g. "01001100100011011111001000001111"). The ToString method creates a similar format (with no work from the developer needed), which you can parse to get just the binary parts. Other than that, I don't know that the BitVector32 is very useful.

There is also a BitStream project on CodeProject that allows variable-sized binary containers. I've used it when I had to pack a collection of bytes into a new structure with different size-boundaries (10- and 11-bit values packed into a bunch of bytes). I think that I could have used the BitArray class for that application, too.

Got a method you use for binary manipulation? Leave a comment.

  1. See comments

Report this snippet  

You need to login to post a comment.