位于twiddling网站的问题

dat*_*ili 3 code-analysis bit-manipulation

这是代码:

unsigned int v;  // word value to compute the parity of
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return (0x6996 >> v) & 1;
Run Code Online (Sandbox Code Playgroud)

它计算给定单词的奇偶校验v.0x6996是什么意思?

二进制数0x6996是110100110010110.

int*_*jay 8

前四行转换v为4位数(0到15),具有与原始相同的奇偶校验.16位数字0x6996包含从0到15的所有数字的奇偶校验,右移用于选择正确的位.它类似于使用查找表:

//This array contains the parity of the numbers 0 to 15
char parities[16] = {0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0};
return parities[v];
Run Code Online (Sandbox Code Playgroud)

请注意,数组条目与0x6996的位相同.使用(0x6996 >> v) & 1给出相同的结果,但不需要内存访问.