Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a BitArray

Tags:

d

bitarray

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?

like image 934
Byakkun Avatar asked Jun 24 '11 14:06

Byakkun


1 Answers

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.

like image 175
Peter Alexander Avatar answered Oct 11 '22 10:10

Peter Alexander