实例三十:与或位运算
问题描述:
编写一个程序,其功能是将正整行数组中所有元素转换为不大于它们的最大偶数,并显示输出。
Write a program whose function is to convert all elements in a positive entire row array to no more than their largest even number and display the output.
算法思路:
- 只需要将该正整数所对应的二进制数的最低位清零。
It is only necessary to clear the lowest bit of the binary number corresponding to the positive integer. - “按位与”运算有将数据中指定位清零的功能,如果将数 x 的第 n 和 m 位清零,就将 x 与 y 作“按位与”运算,其中 y 所对应的二进制数除了第 n 和 m 位为 0 外,其他位都为 1 。
The “Bitwise AND” operation has the function of clearing the specified bit in the data. If the nth and mth bits of the number x are cleared, x and y are “bitwise AND”, where the binary number corresponding to y All bits except the nth and m bits are 0.
#include<stdio.h>
#define N 10
int main(void)
{
int k,a[N];
printf("Input a:\n");
for(k=0;k<N;k++)
scanf("%d",&a[k]);
printf("The original array is:\n");
for(k=0;k<N;k++)
printf("%4d",a[k]);
printf("\n");
for(k=0;k<N;k++)
a[k]=a[k]&0xfffe; //将 N 个正整数转换为不大于它的最大偶数
printf("The converted array is:\n");
for(k=0;k<N;k++)
printf("%4d",a[k]);
printf("\n");
return 0;
}
程序心得:
- 将一个正整数所对应的二进制数的最低位清零,就是这个正整数合一个最低位为 0 其余位为 1 的 16 位(整数占两个字节)数进行 “按位与” 操作,即与 1111111111111110 (对应的十六位进制数为 fffe)进行 “按位与” 运算。
Clearing the least significant bit of the binary number corresponding to a positive integer, that is, the positive integer and the lowest bit are 0, and the remaining bits are 1 bit (the integer is two bytes) for the “bitwise AND” operation, ie Perform a “bitwise AND” operation with 1111111111111110 (the corresponding hexadecimal number is fffe).