位操作习题1

/*
位操作运算练习
将某无符号整型数据的第0-3位清零
将某无符号整型数据的第4-7位置1
将某无符号整型数据的第0-3位取反
*/

#include <stdio.h>

int main(void)
{
	unsigned n;
	scanf("%x", &n);
	printf("0-3 clear:0x%x\n", n & 0xfffffff0);
	printf("4-7 set 1:0x%x\n", n | 0x000000f0);
	printf("0-3 set ~:0x%x\n", n ^ 0x0000000f);

	return 0;
}
//判断某个数是奇数还是偶数

#include <stdio.h>

int main(void)
{
	unsigned n,tmp;
	scanf("%x", &n);
	tmp = n & 0x00000001;
	if(tmp == 0x01){
		printf("odd\n");
	}else printf("even\n");
	


	return 0;
}
/*
通过位运算将整型数据的某些位清零
通过位运算将整型数据的某些位置1
unsigned cleanbits(unsigned int n, int start, int end)
unsigned setbits(unsigned int n, int start, int end)

*/

#include <stdio.h>

unsigned cleanbits(unsigned n, int start, int end)
{	
	unsigned tmp;
	tmp = n &  ~( ~( (~0) << (end - start + 1) ) << start );
	printf("before:0x%x\ncleanbits:0x%x\n", n, tmp);
	return 0;
}
unsigned setbits(unsigned n, int start, int end)
{	
	unsigned tmp;
	tmp = n | ~( (~0) << (end - start + 1) ) << start;
	printf("before:0x%x\nsetbits:0x%x\n", n, tmp);
	return 0;
}


int main(void)
{
	unsigned n;
	int start, end;
	printf("输入整形数据n,起始bits位start的值,结束bits位end的值\n");
	scanf("%x%d%d", &n, &start, &end);
	cleanbits(n, start, end);
	setbits(n, start, end);
	return 0;
}<pre name="code" class="cpp">
输入整形数据n,起始bits位start的值,结束bits位end的值
256 0 3
before:0x256
cleanbits:0x250
before:0x256
setbits:0x25f
etbits(unsigned intn, intstart, intend)

 
 
位操作习题1_第1张图片 位操作习题1_第2张图片

你可能感兴趣的:(位操作习题1)