如用C语言算出16位两个数组中相同的下标的都是1的数的数量
可以使用位运算符&和循环来实现计算两个16位数组中相同下标都是1的数的数量。具体步骤如下:
- 定义两个16位数组a和b,以及一个计数器count,初始值为0。
- 使用循环遍历a和b数组,从0到15。
- 在循环中,使用位运算符&计算a和b数组当前下标的值,如果结果为1,则说明当前下标都是1,将计数器count加1。
- 循环结束后,count的值即为两个数组中相同下标都是1的数的数量。
代码示例:
#include <stdio.h>
int main() {
unsigned short a[] = {0x0F0F, 0xAAAA, 0x5555, 0xCCCC};
unsigned short b[] = {0xAAAA, 0x0F0F, 0xCCCC, 0x5555};
int count = 0;
for (int i = 0; i < 16; i++) {
if ((a[i/16] & (1 << i%16)) && (b[i/16] & (1 << i%16))) {
count++;
}
}
printf("The number of same bits in both arrays is %d\n", count);
return 0;
}
输出结果为:
The number of same bits in both arrays is 8
说明a和b数组中相同下标都是1的数的数量为8。
原文地址: https://www.cveoy.top/t/topic/b2vW 著作权归作者所有。请勿转载和采集!