gpt4 book ai didi

c - 按位比较

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:50 26 4
gpt4 key购买 nike

我有一个表示 8x8“位” block 的数组

unsigned char plane[8]

我想做的是水平循环这个“位” block 并计算变化发生的次数10

当我提取一点时,它被存储在一个unsigned char,所以基本上我想增加一个计数当一个字符为非零而另一个为零时。

我有以下内容:

int getComplexity(unsigned char *plane) {
int x, y, count = 0;
unsigned char bit;

for(x = 0; x < 8; x++) {
for(y = 0; y < 8; y++) {
if(y == 0) {
bit = plane[x] & 1 << y;
continue;
}

/*
MISSING CODE
*/
}
}
}

对于缺失的代码,我可以这样做:

if( (bit && !(plane[x] & 1 << y)) || (!bit && (plane[x] & 1 << y)) ) {
bit = plane[x] & 1 << y;
count++;
}

然而,我真正想看到的是是否有一些巧妙的按位操作来代替执行此步骤有两个单独的测试。

最佳答案

这实际上只是一个 gcc 解决方案,因为 popcnt 内在函数不适用于所有其他编译器。

unsigned char plane[8];

static const uint64_t tmask = 0x8080808080808080UL;

uint64_t uplane = *(uint64_t *)plane; // pull the whole array into a single uint

return __builtin_popcnt( ~tmask & (uplane ^ (uplane >> 1) ) );

对于 x86,popcnt 指令直到 sse4.2 才真正实现(最近)。此外,虽然这看起来依赖于字节顺序,但它并不依赖于字节顺序,因为由于掩码,不允许任何单个字节进行交互。它正在对内存的工作方式做出一些假设:\

作为旁注,在“水平”方向上做同样的事情同样简单:

return __builtin_popcnt(0xFFFFFFFFFFFFFFUL & ( uplane ^ (uplane >> 8) ) );

关于c - 按位比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491624/

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