1.题目:请编写一个c函数,该函数给出一个字节中被置为1的位的个数
# include <stdio.h>
int main()
{
char ch;
int index = 0;
int count = 0;
printf("please input the string: \n");
scanf("%c",&ch);
while(index < 8)
{
if((ch | 1) == ch)
{
count ++;
}
ch = ch >> 1;
index ++;
}
printf("%d",count);
return 0;
}
利用按位或的方式,将ch与1按位或,之后的结果与ch比较,同则该位为1,不同则为0,之后再将ch进行右移,循环到结束。
2.题目:输入一个整数a,再输入两个整数p1,p2(p1,p2<32),输出该整数的二进制表示方法中从右端开始的p1到p2位.
# include <stdio.h>
# include <math.h>
int main()
{
int a;
int p1,p2;
int index;
int sum = 0;
printf("please input a: \n");
scanf("%d",&a);
printf("please input p1 and p2: \n");
scanf("%ld,%ld",&p1,&p2);
index = pow(2,(p1 - 1));
while(sum < (p2 - p1))
{
if((a | index) == a)
{
printf("1");
}
else
{
printf("0");
}
index = index << 1;
sum ++;
}
return 0;
}
1 2 3 几题思路都差不多。
3.题目:输入一个整数a,再输入两个整数p1,p2(p1,p2<32),将该整数的二进制表示方法中从右端开始的p1到p2位取反后输出
# include <stdio.h>
# include <math.h>
int main()
{
int a;
int p1,p2;
int index;
int sum = 0;
printf("please input a: \n");
scanf("%d",&a);
printf("please input p1 and p2: \n");
scanf("%ld,%ld",&p1,&p2);
index = pow(2,(p1 - 1));
while(sum < (p2 - p1))
{
if((a | index) == a)
{
printf("0");
}
else
{
printf("1");
}
index = index << 1;
sum ++;
}
return 0;
}
4.题目:输入一个整数a,再输入两个整数p(p<32),v(0|1),将该整数a的p位设置为v,输出修改后的该整数的二进制表示.
# include <stdio.h>
# include <math.h>
int main()
{
int a;
int p;
int v;
int sum = 0;
int index = 31;
int array[index];
printf("please input a: \n");
scanf("%d",&a);
printf("please input p(p < 32): \n");
scanf("%d",&p);
printf("please input v(0 | 1): \n");
scanf("%d",&v);
switch (v)
{
case 1:
{
a |=(1 << (p - 1));
break;
}
case 0:
{
a &= ~(1 << (p - 1));
break;
}
default:
{
break;
}
}
while(sum < 32)
{
if((a | 1 )== a)
{
array[index] = 1;
}
else
{
array[index] = 0;
}
a = a >> 1;
sum ++;
index --;
}
for(index = 0;index < 32;index ++)
{
printf("%d",array[index]);
}
return 0;
}
主要掌握位操作中,对于指定位如何置0或1.
5.题目:输入一个32位的整数a,使用按位异或^运算,生成一个新的32位整数b,使得该整数b的每一位等于原整数a中该位左右两边两个bit位的异或结果
提示:0 ^ 0 = 0; 1 ^ 1 = 0; 0 ^ 1 = 1; 1 ^ 0 = 1;
# include <stdio.h>
# include <math.h>
int main()
{
int a;
int b = 0;
int index,index2;
int array[100],array1[100];
int num;
printf("please input a: \n");
scanf("%d",&a);
index = 0;
while(index < 32)
{
if((a | 1) == a)
{
array[index] = 1;
}
else
{
array[index] = 0;
}
a = a >> 1;
index ++;
}
index2 = 0;
for(index = 0;index < 32;index ++)
{
if(index ==0 || index == 31)
{
array1[index2] = array[index] ^ 0;
}
else
{
array1[index2] = array[index - 1] ^ array[index + 1];
}
index2 ++;
}
for(index2 = 0;index2 < 32;index2 ++)
{
if(array1[index2] == 1)
{
num = pow(2,index2);
b = b + num;
}
}
printf("%d",b);
return 0;
}
主要的困惑在于第一位和最后一位是怎么弄得。