登录
    Technology changes quickly but people's minds change slowly.

掩码的使用

技术宅 破玉 1173次浏览 0个评论

什么是掩码

掩码是通过按位与运算,设置为开(1)或者关(0)的位组合,例如我们定义一个符号常量MASK为2,(二进制形式为00000010),只有1号位是1,那我们将MASK 与任意值按位与,那么任意值除1号位不变化之外,其他位都会变为0,因为按位
与(&) 任何位与0组合都会变成0,这个过程叫做使用掩码

利用掩码计算十进制的二进制表示

#include <stdio.h>
#include <limits.h>
char * itobs(int,char *);
void show_sbtr(const char *);

int main (void){
    char bin_str[CHAR_BIT*sizeof(int)+1];
    int number;
    puts("Enter integers and see them in binary:");
    puts("Non-numeric input terminate program:");
    while (scanf("%d",&number)==1){
        itobs(number,bin_str);
        printf("%d is ", number);
        show_sbtr(bin_str);
        putchar('\n');
    }
    puts("Bye!");
    return 0;
}

char * itobs(int n,char * ps){
    int i;
    const static int size=CHAR_BIT*sizeof(int);
    for (i = size-1;  i>=0 ; i--,n>>=1) {
       ps[i]=(01&n)+'0';
    }
    ps[size]='\0';
    return ps;
}

void show_sbtr(const char * str){
    int i=0;
    while (str[i]){
        putchar(str[i]);
        if(++i%4==0&&str[i]){
            putchar(' ');
        }
    }
}

在函数 itobs 中01&n 表示的就是n 的最后一位的值,然后每次循环 n 右移 1位,最终就是n的二进制表示了


华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明掩码的使用
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址