Convert BitArray to a small byte array

I've read the other posts on BitArray conversions and tried several myself but none seem to deliver the results I want.

My situation is as such, I have some c# code that controls an LED strip. To issue a single command to the strip I need at most 28 bits

1 bit for selecting between 2 led strips

6 for position (Max 48 addressable leds)

7 for color x3 (0-127 value for color)

Suppose I create a BitArray for that structure and as an example we populate it semi-randomly.

        BitArray ba = new BitArray(28);

        for(int i = 0 ;i < 28; i++)
        {
            if (i % 3 == 0)
                ba.Set(i, true);
            else
                ba.Set(i, false);
        }

Now I want to stick those 28 bits in 4 bytes (The last 4 bits can be a stop signal), and finally turn it into a String so I can send the string via USB to the LED strip.

All the methods I've tried convert each 1 and 0 as a literal char which is not the goal.

Is there a straightforward way to do this bit compacting in C#?

Jon Skeet
people
quotationmark

Well you could use BitArray.CopyTo:

byte[] bytes = new byte[4];
ba.CopyTo(bytes, 0);

Or:

int[] ints = new int[1];
ba.CopyTo(ints, 0);

It's not clear what you'd want the string representation to be though - you're dealing with naturally binary data rather than text data...

people

See more on this question at Stackoverflow