1、 輸入一個整數(shù)a,再輸入兩個整數(shù)p1,p2(p1,p2<32),將該整數(shù)的二進制表示方法中從右端開始的p1到p2位取反后輸出
/*****************************************************copyright (C), 2016-2017, Lighting Studio. Co., Ltd. File name:Author:王 Version:0.1 Date: Description:Funcion List: *****************************************************/#include <stdio.h>int main(){ int a,p1,p2,temp1; int i,mask; PRintf("Enter the number:"); scanf("%d",&a); printf("choose the number between p1 to p2:"); scanf("%d%d",&p1,&p2); if(p1>p2) // 如果p1>p2 時進行數(shù)據(jù)交換 { p1 = p1 + p2; p2 = p1 - p2; p1 = p1 - p2; } if(p1 <= p2) { temp1 = a >> (p1-1); // 將這個數(shù)右移,使得所需要的位數(shù)是從最右端開始 } for(i=(p2-p1);i>=0;i--) // 選取p1和p2之間的這段位數(shù) putchar(((temp1 >> i) & 1) ? '0' : '1'); // 輸出這個數(shù)如果是1,則輸出0,實現(xiàn)取反 printf("/n"); return 0;}2、輸入一個整數(shù)a,再輸入兩個整數(shù)p(p<32),v(0|1),將該整數(shù)a的p位設置為v,輸出修改后的該整數(shù)的二進制表示.
/*****************************************************copyright (C), 2016-2017, Lighting Studio. Co., Ltd. File name:Author:王 Version:0.1 Date: Description:Funcion List: *****************************************************/#include <stdio.h>#include <string.h>int main(){ int a,p,v,mask,i; printf("Enter a number:"); scanf("%d",&a); printf("Enter the location:"); scanf("%d",&p); printf("choose 0 or 1:"); scanf("%d",&v); if(v == 0) //判斷置0還是置1 { mask = ~(1 << p-1); // 設計掩碼,使得所需要置0的那一位為0 a = (a & mask); // 按位與 實現(xiàn)清零 } else { mask = (1 << p-1); // 需要置1的那一位保持為1,其余為0,使用按位或 實現(xiàn)置1 a = (a | mask); } printf("The answer is:"); for(i=sizeof(a);i>=0;i--) printf("%d",(a>>i)&1); printf("/n"); return 0;}
新聞熱點
疑難解答