如何分割 BitArray

发布于 2024-11-16 19:14:36 字数 331 浏览 3 评论 0原文

我需要将 BitArray (来自 std.bitmanip)分成两半。到目前为止,我发现切片没有实现,迭代它并附加或分配总是会产生超出范围的异常。我尝试将其转换为其他类型(它适合 long/ulong),但这似乎太麻烦,并且当我尝试初始化新的 BitArray 时,它也会给我一个超出范围的异常,如下所示

BitArray[] C, D;
long lg = toLong(bitArr);
C[0].init(cast(void[])((lg >> 28) & 0x0fff_ffff), 28);

:我的问题有更简单的解决方案吗?如果不是,我做错了什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时间你老了 2024-11-23 19:14:36

以天真的方式这样做有什么问题吗?

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];

我在一个小测试用例上尝试了这个,它对我来说效果很好。

您的代码不起作用的原因是数组 C 的长度为零,因此访问 C[0] 是非法的。您需要首先添加一个空的 BitArray

C ~= BitArray();

或者,也可以使用静态数组:

BitArray[1] C, D;

注意:如果您不需要保留原始数组,则只需使用以下命令即可将其切成两半:

A.length /= 2;

当然,您需要先复制后半部分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文