我试图使用一个简单的循环来查找数字的奇偶校验,该循环检查每个设置位并递增计数器。我似乎在32位以外的地址有一个额外的位。例如,当试图找到1的奇偶校验时,奇偶校验应该是奇数并且具有' 1'在索引0,我得到一个' 1'在索引0和32.任何帮助将不胜感激。代码和输出如下:
C ++代码:
#include <cstdio>
#include <cstdlib>
bool compute_parity(int64_t val){
int int_size = 64;
int par_sum = 0;
printf("indexes where there are '1's:\n");
for(int i=0; i<int_size;i++){
if(val & 1<<i){
printf("%d\n", i);
par_sum++;
}
}
printf("\n");
printf("number of '1's: %d\n", par_sum);
printf("\n");
if(par_sum & 1)//if par_sum is odd
return true;
return false;
}
int main(){
//int64_t val = 9223372036854775807;
int64_t val = 1;
printf("parity: %s\n", compute_parity(val) ? "odd" : "even");
}
compute_parity(1)的输出:
indexes where there are '1's:
0
32
number of '1's: 2
parity: even