Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top