views:

588

answers:

2

I'm working on a TCP based application that processes bitpacked messages, meaning: The messages transmitted/received are not byte aligned. For instance 3 bits represent field 1, where 19 bits may represent field 2. My question is, does anyone know of a C# library that can take a set of bytes and set/get an arbitrary range of bits within those bytes? I've seen & created similar utilities in C/C++ but I need a 100% C# solution and I don't want to re-invent the wheel again.

I've looked at the BitArray class, but it doesn't allow for referencing arbitrary ranges of bits.

+2  A: 

I'm not aware of any bcl classes that provide what you want. But you can use bitwise operations (shift, and, or, ...) to extract the fields of your interest.

For instance, to get a field starting at bit 2 with a size of 5 bits use:

int extract = (source & 0x7C) >> 2;
Martijn
This is the method I'm using in my current C++ implementations. I was hoping I didn't have to port the implementation to C# and could use a 3rd party library. I'm interested in some slick C# library to accomplish this. I just didn't want to "re-invent the wheel" again.
nathan
+1  A: 

Check out this CodeProject solution - it is a open source managed BitStream class callable from C#.

LBushkin
Perfect. Exactly what I was looking for.
nathan