Is there an easy way to merge several BitArrays?

152 Views Asked by At

I have several BitArrays that will need to be merged to into 48 byte structure.

BitArray a1 = new (3);
BitArray a2 = new (11);
BitArray a3 = new (14);
//And so on

//Do bit manipulation, etc with the individual Arrays.

Ultimately, I want appended all the together and return a byte[] so I can send them out via UDP. I was thinking of keeping them in an array / list of just iterate thru them and dump them into an ulong - > byte[]

1

There are 1 best solutions below

6
Sweeper On

According to this, there isn't really a better way to concatenate two BitArrays than just "doing it step by step" - make a bool[] for the result, copy each BitArray into there, and then make a new BitArray from the bool[].

BitArray ConcatenateAll(params BitArray[] arrays) {
    var bools = new bool[arrays.Sum(a => a.Count)];
    var index = 0;
    foreach (var array in arrays) {
        array.CopyTo(bools, index);
        index += array.Count;
    }
    return new BitArray(bools);
}

Since you want a byte[], you can do:

var bitArray = ConcatenateAll(bitArr1, bitArr2, ...);
var bytes = new byte[48];
bitArray.CopyTo(bytes, 0);

Note that you can also convert the bool[] directly into a byte[] by bit operations if performance is important, like in this answer.