Arithmetic

C语言-位运算

PineappleCat · 5月25日 · 2019年 617次已读

Description
键盘输入一个整数(正、负、0均可),求其补码或原码(后面输入的数是1则求原码,若是2则求补码)

Input

任意int型数据,然后再输入一个整数决定求原码还是补码(1—-原码,2—补码)

Output
原码或补码

Sample Input
100 1
Sample Output
00000000000000000000000001100100

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n,i;
    char k;
    scanf("%d %c",&n,&k);
    while(k!='1'&&k!='2'){
        k=getchar();
    }
    if(k=='1'&&n<0){
        n--;
        n^=~0;
        n|=1<<sizeof(int)*8-1;
    }
    for(i=sizeof(int)*8-1;i>=0;i--){
        printf("%d",n>>i&1);
    }
    printf("\n");
    return 0;
}

Click here to view the copyright notice of this site(点击此处查看本站版权声明)
0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!