I need to split an BitArray (from std.bitmanip) into its halfs. Until now I've found out that slicing is not implemented, iterating over it and appending or assigning produces Out of range exception invariably. I've tried to convert it into some other type (it fits into long/ulong) but that seems like too much trouble and it also give me an out of range exception when i try to init the new BitArrays as seen below:
BitArray[] C, D;
long lg = toLong(bitArr);
C[0].init(cast(void[])((lg >> 28) & 0x0fff_ffff), 28);
Is there a simpler solution for my problem? If not, what am I doing wrong?
What's wrong with doing it the naive way?
BitArray A, B, C;
A = /* ... */
// Split A into B & C
auto n = A.length;
B.length = n/2;
foreach (i; 0..n/2)
B[i] = A[i];
C.length = n - n/2;
foreach (i; n/2..n)
C[i-n/2] = A[i];
I tried this on a little test case and it worked fine for me.
The reason your code doesn't work is because the length of array C
is zero, so accessing C[0]
is illegal. You'd need to add an empty BitArray
first.
C ~= BitArray();
Or, alternatively, use a static array:
BitArray[1] C, D;
Note: If you don't need to keep the original array, then you can cut it in half by simply using:
A.length /= 2;
Of course, you'll need to copy the second half first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With