C语言位运算练习题1

时间:2023-02-23 15:25:01

1,

#include <stdio.h>

int bit_1(int x)
{
    int i;
    int y;
    int sum = 0;
    for(i = 0 ; i < 8 ; i++)    
    {
        y = x % 2;   
        x = x / 2;
        if(y == 1)
        {       
            sum  = sum + 1;
        }
    }
    return sum;  
}

int main()
{
    int x;

    printf("please input x \n");
    scanf("%d",&x);
    printf("the number of '1' is %d\n",bit_1(x));

    return 0;
}

2,

#include <stdio.h>

#define MAX 32

void deal(int n,int p1,int p2,int num[])  
{  
    int i;

    int temp = 0;
    int k = 0;

    int a[MAX];

    for(i = p1 - 1; i <= p2; i++)  
    {  
        temp = ( n >> i ) & 1;   
        num[k] = temp;  
    k++;  
    }  
}  

void output(int p1,int p2,int num[])  
{
    int i;
    int n;

    n = p2 - p1;

    for(i = n; i >= 0; i--)  
    {  
        printf("%d",num[i]);  
    }  
}

int main()  
{  
    int n;
    int p1,p2;

    int num[MAX]={0};

    printf("please input the int:");
    scanf("%d",&n);

    printf("please input p1,p2:");
    scanf("%d %d",&p1,&p2);

    deal(n,p1,p2,num);

    output(p1,p2,num);
    printf("\n");

    return 0;  
}