实例三十:与或位运算

实例三十:与或位运算

问题描述:
编写一个程序,其功能是将正整行数组中所有元素转换为不大于它们的最大偶数,并显示输出。
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).
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值