gpt4 book ai didi

C语言高效数组掩码

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:37 25 4
gpt4 key购买 nike

我有两个 3 维 BOOL 数组,我想在它们之间进行屏蔽。我的意思是创建第三个数组:third[i][j][k] = first[i][j][k] && second[i][j][k],对于每个 i, j,k.

  1. 我用c语言(可能是汇编)
  2. 我需要掩码操作尽可能快
  3. 可以假设第一个和第二个具有相同的大小。
  4. 如果它可以提高性能,我可能会将数据从数组重新排列为其他数据排列方式。

编辑:每个数组维度为100

谢谢!

最佳答案

我在评论中提到了这一点,但这里有一些工作代码(希望如此。我没有测试它,也没有通过编译器提供它。这只是为了这个想法)。如果您有一个 100x100x100 阵列,您正试图将其建模为位掩码,那么您可以执行以下操作:

// Create two bitmasks
const unsigned int BITS_PER_BYTE = 8;
const unsigned int DIM = 100;
const unsigned int BITS_PER_VALUE = BITS_PER_BYTE * sizeof(unsigned long);
const unsigned long MASK_SIZE = (DIM * DIM * DIM) / BITS_PER_VALUE;
unsigned long bitmask1[MASK_SIZE] = {0};
unsigned long bitmask2[MASK_SIZE] = {0};
unsigned long bitmask_result[MASK_SIZE];

// Set the two bitmasks, this is probably sub-optimal but you
// mention that setting bitmasks isn't supposed to be overly performant

// set bitmask1 (repeat something similar for bitmask2)
for (int i = 0; i < DIM; ++i)
for (int j = 0; j < DIM; ++j)
for (int k = 0; k < DIM; ++k) {
// set bitmask[i][j][k] to 1
unsigned int offset = DIM*DIM*i + DIM*j + k;
unsigned int long_offset = offset / BITS_PER_VALUE;
unsigned int bit_offset = offset % BITS_PER_VALUE;
// XXX SET THIS TO WHATEVER VALUE YOU HAVE, 1 FOR true and 0
// FOR false. I'M SETTING EVERYTHING TO TRUE FOR THE SAKE OF
// EXAMPLE
bitmask1[long_offset] = 1 << bit_offset;
}

// Now to actually compare:
for (int i = 0; i < MASK_SIZE; ++i) {
bitmask_result[i] = bitmask1[i] & bitmask2[i];

// and that's it. bitmask_result will now have your answers. decompose
// the bitmask by doing the reverse of the above set loop

关于C语言高效数组掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7086013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com